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

标签 c++ copy-constructor

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

最佳答案

编译器生成的复制构造函数进行成员复制。有时这还不够。例如:

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

关于c++ - 我们什么时候必须使用复制构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3278625/

相关文章:

c++ - 如何更改我的应用程序使用的 .dll 搜索路径?

c++ - 为具有许多变体的类存储默认值的推荐方法是什么?

c++ - 为什么这种隐式转换如何以及为何起作用

c++ - 关于一段带有模板、转换运算符和复制构造函数的代码的问题

c++ - 抽象类,拷贝构造函数

c++ - 为什么 C++ 编译器在类具有引用成员时不删除复制构造函数?

c# - 仅通过 WINAPI 检查 Winform CheckBox 是否被选中

c++ - 模板类的二元运算符不解决隐式转换

c++ - 模板化复制构造函数因特定模板化类型而失败

c++ - GLSL 类型不一致