简体   繁体   English

如何在C ++中通过引用复制对象?

[英]How to copy an object by reference in C++?

I have following case. 我有以下情况。 That's what I'm trying to do: 那就是我想要做的:

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

How to properly copy that object to shape2? 如何正确地将该对象复制到shape2? I need two copies of that object which will be stored in shapesArr[ 0 ] and shape2 separately. 我需要该对象的两个副本,这些副本将分别存储在shapesArr [0]和shape2中。

You can use Shape *shape2 = new Shape(shapesArr[0]); 您可以使用Shape *shape2 = new Shape(shapesArr[0]); to create a copy. 创建副本。

There are two errors in your code: 您的代码中有两个错误:

First: 第一:

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 );

Second, you can't delete the vector, because you didn't new a vector, if you want to erase all the element in the vector, use shapesArr.clear() or shapesArr.erase(shapesArr.begin(),shapesArr.end()); 其次,您不能删除矢量,因为您没有新建矢量,如果要擦除矢量中的所有元素,请使用shapesArr.clear()shapesArr.erase(shapesArr.begin(),shapesArr.end());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM