在本身使用 new 分配的对象内部使用“new”分配内存是否有任何影响。在编译器、链接器、运行时性能或其他方面有什么优势或劣势吗?
我正在谈论的一个例子
class IntData
{
public:
IntData()
{
IntVector = new std::vector<int>();
//...
}
protected:
std::vector<int> *IntVector; //Would this be any different to static allocation if...
};
//...I know that all IntData objects will be dynamically allocated
IntData *object = new IntData();
最佳答案
使用
std::vector<int> IntVector;
您正在为您的 vector 提供自动存储(即,如果在函数中,它将位于堆栈空间中,如果是类的成员,则取决于父对象的方式分配..在上面的例子中:在堆上)
使用
IntVector = new std::vector<int>();
您正在堆上完全分配对象,包括一些容器的内部数据(对象将始终复制到堆上)。
这样做值得吗?
对于一小串字节:通常没有。此外,您必须通过调用 delete
自行记录内存。可能不是问题,但在上面的简单案例中,我认为没有理由这样做。
也与更一般的情况有关:STL containers on the stack and the heap 和 Object creation on the stack/heap?
关于c++ - 动态分配对象内部的动态分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23854291/