用虚方法实例化类,但不进行堆分配
Instantiating a class with virtual methods without a heap allocation
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;
}
我想达到的目的:
- 我需要实例化一个具有虚拟方法的类。
- 在我确切地知道要实例化哪个派生类的时间点上,我不能进行进一步的堆分配(这只是出于好奇,所以确切的原因无关)。
- 因此,我想以某种方式预先分配足够的空间来容纳任何可能的实现,然后再决定我要在其中实例化什么类。
上述代码中是否存在任何不符合标准/未定义的行为?
代码正确。请参阅对该问题的评论,以获得一些有趣的见解,特别是std::aligned_union
的使用,它可以用作上述PreallocatedStorage
联合的通用替代品。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有没有一种方法可以使用placement new将堆叠对象分配给分配的内存
- GlobalAlloc而不是其他分配方法
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- 拥有映射的现代方法,该映射可以指向或引用已在堆栈上分配的不同类型的数据
- 使 std::vector 分配对齐内存的现代方法
- 使用同一类中的方法重新分配字段时出现问题
- 工厂方法:分配和strcpy_s的差异
- 在类中分配具有方法值的变量
- 删除类成员的动态分配内存的最佳方法是什么
- 将共享指针传递给函数参数 - 将其分配给局部变量的正确方法是什么
- const_cast const 方法中的"this"将"this"分配给外部变量?
- 使用类中的方法作为运算符将值分配给类的私有成员
- 释放分配给大量矢量的内存的最有效方法是什么?
- C++类内部结构动态分配的方法
- 为大无符号整数分配内存的有效方法
- C ++中新分配的int的内存大小,有没有不同更好的方法来查看它?
- c++内存分配方法
- 两种C++分配方法有什么区别
- c++在构造函数中使用指向其他方法的指针分配方法:我做错了什么?