-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中。
您沒有爲'new'分配'shapesArr',爲什麼要調用'delete'呢? – Arash
你的'vector'存儲'Shape',你爲堆分配'Shape',然後忽略它和'push_back'類,而不是實例(即使你是'push_back'-ed'shape', ,因爲'vector'存儲'Shape',而不是'Shape *')。你也試着'''''''''''''''''''甚至不在堆上。這段代碼永遠不會編譯。請製作[MCVE];這是沒用的。我懷疑這裏的真正答案是「根本不使用堆,一切正常」。 – ShadowRanger