我们什么时候必须使用复制构造函数?

我们什么时候必须使用复制构造函数?

我知道C ++编译器会为一个类创建一个副本构造函数。在哪种情况下,我们必须编写用户定义的副本构造函数?你能举一些例子吗?



偶然的你
浏览 583回答 4
4回答

慕斯王

编译器生成的副本构造函数执行成员级复制。有时这还不够。例如: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;}在这种情况下,成员的成员级复制stored将不会复制缓冲区(仅会复制指针),因此共享缓冲区的第一个要销毁的副本将delete[]成功调用,而第二个将遇到未定义的行为。您需要深度复制副本构造函数(以及赋值运算符)。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;

哈士奇WWW

如果您具有动态分配内容的类。例如,将书名存储为char *并将书名设置为new,则复制将不起作用。您将必须编写一个复制构造函数,title = new char[length+1]然后执行strcpy(title, titleIn)。复制构造函数只会执行“浅”复制。
打开App,查看更多内容
随时随地看视频慕课网APP