我们什么时候必须使用复制构造函数? [英] When do we have to use copy constructors?
问题描述
因为我知道C ++编译器为每个类创建一个复制构造函数。在哪些情况下我们必须写用户定义的复制构造函数?你能举一些例子吗?
As I know that C++ compiler creates a copy constructor for each class. In which cases we have to write user defined copy constructors? Can you give some examples?
推荐答案
由编译器生成的复制构造函数执行成员式复制。有时这是不够的。例如:
The copy constructor generated by the compiler does member-wise copying. Sometimes that is not sufficient. For example:
class Class {
public:
Class( const char* str );
~Class();
private:
char* stored;
};
Class::Class( const char* str )
{
stored = new char[srtlen( str ) + 1 ];
strcpy( stored, str );
}
Class::~Class()
{
delete[] stored;
}
在这种情况下成员方式复制 / code>成员不会复制缓冲区(只有指针会被复制),所以首先被销毁的复制共享缓冲区将调用
delete []
成功第二个会遇到未定义的行为。您需要深复制复制构造函数(以及赋值运算符)。
in this case member-wise copying of stored
member will not duplicate the buffer (only the pointer will be copied), so the first to be destroyed copy sharing the buffer will call delete[]
successfully and the second will run into undefined behavior. You need deep copying copy constructor (and assignment operator as well).
Class::Class( const Class& another )
{
stored = new char[strlen(another.stored) + 1];
strcpy( stored, another.stored );
}
void Class::operator = ( const Class& another )
{
char* temp = new char[strlen(another.stored) + 1];
strcpy( temp, another.stored);
delete[] stored;
stored = temp;
}
这篇关于我们什么时候必须使用复制构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!