2017-03-18 90 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