小编Mag*_*GAT的帖子

复制赋值运算符说明

我正在为我创建的一个类编写一个复制赋值运算符,我使用以前的帖子作为指导: 什么是三法则?

我对这个人解释的一个方面有点困惑。

这是他们的课:

class person
{
    char* name;
    int age;
};
Run Code Online (Sandbox Code Playgroud)

这是我用作参考的复制赋值运算符定义(至少提供了 2 个):

// 2. copy assignment operator
person& operator=(const person& that)
{
    char* local_name = new char[strlen(that.name) + 1];
    // If the above statement throws,
    // the object is still in the same state as before.
    // None of the following statements will throw an exception :)
    strcpy(local_name, that.name);
    delete[] name;
    name = local_name;
    age = that.age;
    return *this;
}
Run Code Online (Sandbox Code Playgroud)

我发现令人困惑的是,为什么他们包括这条线delete[] name;

这是他们提供的另一个示例:

person& operator=(const …
Run Code Online (Sandbox Code Playgroud)

c++ class operator-overloading copy-assignment

2
推荐指数
1
解决办法
190
查看次数