为什么不调用复制构造函数?
Why doesn't the copy constructor get called?
我有这个代码复制多边形类。我的问题是,在结束顶点指向原始多边形类的位置。因为似乎没有调用复制构造函数。为什么?
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
类的所有代码,因此不清楚您是否定义了正确的复制赋值和销毁。
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
和其他直接资源管理器)组合在一起。
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 当从函数参数中的临时值调用复制构造函数时
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 使用复制构造函数复制双精度数组
- C 无可行的构造函数复制类型的变量
- 没有可行的构造函数复制类型 'MyString' 的数组元素
- 编译时,复制构造函数/复制分配和正常功能调用优化之间是否存在任何区别
- 如何最小化调用列表构造函数(复制构造函数)的次数?
- C 11矢量构造函数复制与范围
- 我定义了一个非复制构造函数;复制构造函数还会被隐式定义吗
- 可以将构造函数复制为转换运算符
- 将基类指针的构造函数复制到子类
- C++树类:构造函数/复制/内存泄漏
- 如何制作这个在模板构造函数复制中使用类型定义的类型的模板
- 将构造函数复制为模板化的成员函数
- 绕过私有复制构造函数/复制赋值C++
- C++通过构造函数复制对象
- 复制构造函数 - 复制C++中的对象
- 将带unique_ptr的类的构造函数复制到作为成员的抽象类