我遇到了关于C++17 static inline member data
的奇怪行为。有Implementation
抽象类:
class Implementation
{
public:
virtual void call() = 0;
};
有实现抽象类的Example
和AnotherExample
类:
class Example : public Implementation
{
public:
void call() override
{
cout << "Called Example::call function!" << endl;
}
};
class AnotherExample : public Implementation
{
public:
void call() override
{
cout << "Called AnotherExample::call function!" << endl;
}
};
最后有Implementer
类可以使用Example
和AnotherExample
类:
class Implementer
{
private:
static inline Implementation* example = unique_ptr<Example>(new Example).get(); // or make_unique<Example>().get()
static inline Implementation* another_example = new AnotherExample;
public:
static Implementation* get_example(bool flag)
{
// This function returns example object if flag is true otherwise another_example object.
if (flag)
return example;
else
return another_example;
}
};
使用中:
Implementer::get_example(true)->call(); // This expect to return example.
Implementer::get_example(false)->call(); // This expect to return another_example.
我们希望看到这个:
Called Example::call function!
Called AnotherExample::call function!
但是我们看到了:
Called AnotherExample::call function!
Called AnotherExample::call function!
我听不懂。 example
对象如何获取another_example
对象的值?编辑:如果我们进行更改,我们将获得所需的输出
static inline Implementation* example = unique_ptr<Example>(new Example).get();
to
static inline unique_ptr<Implementation> example = unique_ptr<Example>(new Example);