I've encountered a strange behavior about C++17 static inline member data.
There is Implementation abstract class:
class Implementation
{
public:
virtual void call() = 0;
};
There are Example and AnotherExample classes that implement the abstract class:
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;
}
};
Finally there is Implementer class to use Example and AnotherExample classes:
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;
}
};
Using:
Implementer::get_example(true)->call(); // This expect to return example.
Implementer::get_example(false)->call(); // This expect to return another_example.
We expect to see this:
Called Example::call function!
Called AnotherExample::call function!
but we see this:
Called AnotherExample::call function!
Called AnotherExample::call function!
I don't understand it. How does example object get the value of another_example object?
Edit: We can get desired output if we change
static inline Implementation* example = unique_ptr<Example>(new Example).get();
to
static inline unique_ptr<Implementation> example = unique_ptr<Example>(new Example);
Aucun commentaire:
Enregistrer un commentaire