我有以下案例。这就是我想要做的事情:
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 :(得分: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());