为什么不调用复制构造函数?

Why doesn't the copy constructor get called?

本文关键字:构造函数 复制 调用 为什么不      更新时间:2023-10-16

我有这个代码复制多边形类。我的问题是,在结束顶点指向原始多边形类的位置。因为似乎没有调用复制构造函数。为什么?

Polygon::Polygon(const Polygon &aPolyToCopy)
{
int i;
vertices = new Vertex[aPolyToCopy.count];
for (i=0;i<aPolyToCopy.count;i++)
{
    vertices[i].x = aPolyToCopy.vertices[i].x;
    vertices[i].y = aPolyToCopy.vertices[i].y;
}
count = aPolyToCopy.count;
}

在列表模板中,我这样做

template <class T, int i>
bool SortedVector<T, i>::add ( const T& v )
{
myClass[myCurrent] = v; //Copy constructor not called ?
myCurrent++;
return true;
}

模板

 template <class T, int i>
 class SortedVector
 {
 public:
   int maxSize;
   T myClass[i];
   int myCurrent;
   SortedVector();
   ~SortedVector();
   bool add ( const T& v );
};

你正在做一个赋值,你不在这里构造一个新的对象。如果定义自定义复制构造函数,还需要重载operator=

参见http://www.learncpp.com/cpp-tutorial/911-the-copy-constructor-and-overloading-the-assignment-operator/。

如果您要执行类似x = Polygon(y)的操作,则将调用复制构造函数(后面跟着默认的operator=)。但是不要使用这个解决方法,只需提供您的operator=

我认为您的Polygon类中的问题是您有一个vertices数据成员,这似乎是一个原始指针指向Vertex,用于存储与new[]分配的原始数组:

vertices = new Vertex[aPolyToCopy.count];

你可能还需要重载operator=(和析构函数),而不仅仅是复制构造函数(参见三的规则);您没有显示Polygon类的所有代码,因此不清楚您是否定义了正确的复制赋值和销毁。

注意,如果使用健壮的RAII容器类,如 std::vector ,将简化代码。只需添加"std::vector<Vertex> vertices;"数据成员而不是"Vertex* vertices"数据成员,std::vector将负责复制,清理等。你不需要做任何事情:这一切都是由std::vector自动管理的。
#include <vector>    // for std::vector
class Polygon
{
  std::vector<Vertex> vertices;
public:
  explicit Polygon(size_t vertexCount)
    : vertices(vertexCount) // Build a polygon with specified vertices
  {}
  //  
  // Compiler generated copy constructor, operator= and destructor are fine.
  //
};

一般来说,在c++中尝试构建类,将方便的RAII构建块(如std::vector和其他直接资源管理器)组合在一起。