【问题标题】:why copy constructor & assignment operator both are called in this case为什么在这种情况下都调用了复制构造函数和赋值运算符
【发布时间】:2016-05-08 01:29:03
【问题描述】:

谁能解释一下,为什么在我下面的代码中,在 ms3 = ms1 完成的地方,复制和赋值运算符都在这一行中被调用。在上面提到的行中,据我所知,只有重载的赋值运算符应该被调用。但是复制构造函数和赋值运算符都被调用了。请解释一下……为什么会这样?

class MyString {
private:
    char* string;
public:
    MyString(char *ptr = NULL);
    MyString(MyString &str);
    MyString &  operator =(MyString  str);
    ~MyString();
};

MyString::MyString(MyString &str) {
    printf("Copy Constructor called !!!\n");
    int len = strlen(str.string);
    string = new char[len+1];
    strcpy_s(string, len+1, str.string);
}

MyString::MyString(char* str) {
    printf("Constructor called !!!\n");
    if (str != NULL) {
        int len = strlen(str);
        string = new char[len + 1];
        strcpy_s(string, len + 1, str);
    }
    else {
        string = NULL;
    }

}
MyString & MyString::operator=(MyString str) {
    printf("Assignment Operator!!!\n");
    if (&str == this) {
        return *this;
    }

    delete[] string;
    if (&str != NULL) {
        int len = strlen(str.string);
        string = new char[len + 1];
        strcpy_s(string, len+1, str.string);
    }
    return *this;
}
MyString::~MyString() {
    printf("Destructor\n");
    delete[] string;
}

int _tmain(int argc, _TCHAR* argv[])
{
    MyString ms = "ABC";
    MyString ms1("EFG");
    MyString ms2 = ms1;
    MyString ms3;
    ms3 = ms1;
    MyString ms4 = ms3 = ms1;
    return 0;
}

【问题讨论】:

  • if (&str == this) 始终为 false,因为 str 是一个局部变量。 if (&str != NULL) 也始终为真,因为局部变量的地址不能为 0。

标签: c++


【解决方案1】:

赋值运算符按值取参数;复制构造函数用于设置该参数。

【讨论】:

【解决方案2】:

为避免这种情况,您需要重写赋值运算符,使其接受引用,就像复制构造函数一样。你也应该使用const

MyString(MyString const &str);
MyString & operator=(MyString const &str);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 2015-05-21
    • 2019-06-01
    • 2013-05-06
    • 2011-01-16
    相关资源
    最近更新 更多