2017-03-18 48 views
-1

我有以下情况。这就是我想要做的:如何在C++中通过引用复制对象?

std::vector <Shape> shapesArr; 
Shape *shape = new Shape(); 
shape->someParam = someValue; 
shapesArr.push_back(Shape); 

// ... 

Shape *shape2 = new Shape(); 
shape2 = shapesArr[ 0 ]; // <-- here I need a copy of that object to shapeA 

delete[] shapesArr; 
delete shape2; // <-- error, because it has already freed. It would be nice if I had a copy of shapesArr[ 0 ] in my shape2 

如何正确地将该对象复制到shape2?我需要该对象的两个副本,它们将分别存储在shapesArr [0]和shape2中。

+0

您没有为'new'分配'shapesArr',为什么要调用'delete'呢? – Arash

+1

你的'vector'存储'Shape',你为堆分配'Shape',然后忽略它和'push_back'类,而不是实例(即使你是'push_back'-ed'shape', ,因为'vector'存储'Shape',而不是'Shape *')。你也试着'''''''''''''''''''甚至不在堆上。这段代码永远不会编译。请制作[MCVE];这是没用的。我怀疑这里的真正答案是“根本不使用堆,一切正常”。 – ShadowRanger

回答

3

您可以使用Shape *shape2 = new Shape(shapesArr[0]);来创建副本。

有两个错误在你的代码:

第一:

std::vector <Shape> shapesArr; 
Shape *shape = new Shape(); 
shape->someParam = someValue; 
// you should push *shape, because Shape is just the class name 
// and shape is a Shape* type pointer 
// you can shapesArr.push_back(*shape); 
shapesArr.push_back(Shape); 

其次,你不能删除向量,因为你没有新的载体,如果你想删除所有向量中的元素,使用shapesArr.clear()shapesArr.erase(shapesArr.begin(),shapesArr.end());

+0

谢谢!有效! – JavaRunner