我想存储元素(让我们称之为E),但我不知道应该将它们存储为对象还是指向指向动态分配对象的指针。哪个更好:存储对象vs存储指针?
(A,B,C等对象存储有用E的参考)
版本答:
E e;
store.Add(e); //This time the store contains objects.
在这个版本的元素将被复制到商店,但它更容易处理。 (当父对象被销毁的对象将被破坏)
版本B:
E* e = new E();
store.Add(*e); //This time the store contains references.
/*I chose references instead of pointers,
so I have to use pointers only at allocating and deallocating.*/
在这个版本中,没有复制构造。但我必须删除父对象的析构函数中的对象。
哪个更好?为什么?哪些会导致更多的错误,哪些更有效?
你有C++ 11? – Danh
由于这个问题是关于*商店*,所以标准容器中的[object slicing](http://stackoverflow.com/q/274626/3545273)也应该被注意到。 –