class Base
{
public:
virtual ~Base() {}
virtual void Foo() = 0;
};
class FirstDerived: public Base
{
public:
void Foo() { cout << "FirstDerived" << endl; }
};
class SecondDerived: public Base
{
public:
void Foo() { cout << "SecondDerived" << endl; }
};
union PreallocatedStorage
{
PreallocatedStorage() {}
~PreallocatedStorage() {}
FirstDerived First;
SecondDerived Second;
};
class ContainingObject
{
public:
Base* GetObject()
{
if (!m_ptr)
{
// TODO: Make runtime decision on which implementation to instantiate.
m_ptr = new(&m_storage) SecondDerived();
}
return m_ptr;
}
~ContainingObject()
{
if (m_ptr)
{
m_ptr->~Base();
}
}
private:
PreallocatedStorage m_storage;
Base* m_ptr = nullptr;
};
int main()
{
auto object = make_unique<ContainingObject>();
// ...
// Later, at a point where I don't want to make more heap allocations...
// ...
auto baseObject = object->GetObject();
baseObject->Foo();
return 0;
}
我想在这里实现的目标:
上述代码中是否存在任何标准不合规/未定义的行为?
答案 0 :(得分:0)
代码是正确的。请参阅有关该问题的评论,以获取一些有趣的见解,尤其是std::aligned_union
的使用,该PreallocatedStorage
可用作上述queue
联合的通用替代。