C ++赋值运算符“ =”奇怪的行为

时间:2019-10-31 12:22:13

标签: c++ operator-overloading

我有一个非常简单的类名CTable,它包含一个name,一个动态创建的int*整数数组和一个int数组大小。 然后,我声明了默认,参数化和复制的构造函数,并重载了+=运算符。而且我无法理解operator=的怪异行为。

以下是代码片段:

默认构造函数:

CTable::CTable() {
    this->s_name = CTABLE_DEFAULT_NAME;
    cout << "default constr invoked: "+this->s_name << endl;
    this->i_table = new int[CTABLE_DEFAULT_TAB_LEN];
    this->i_table_len = CTABLE_DEFAULT_TAB_LEN;
}//CTable::CTable()

复制构造函数:

CTable::CTable(CTable& rcOther) {
    this->s_name = rcOther.s_name + "_copy";
    cout << "copy constr invoked: " + this->s_name << endl;
    this->i_table = new int[rcOther.i_table_len];
    this->i_table_len = rcOther.i_table_len;
    for (int i = 0; i < rcOther.i_table_len; i++) {
        this->i_table[i] = rcOther.i_table[i];
    }//for (int i = 0; i < pcOther.i_table_len; i++)
}//CTable::CTable(CTable& pcOther)

析构函数:

CTable::~CTable() {
    delete[] (this->i_table);
    cout << "deleting: " + this->s_name << endl;
}//CTable::~CTable()

运算符重载:

CTable CTable::operator+ (CTable& rcOther) {
    CTable pc_new_tab("operator", 1);
    pc_new_tab.bAcc(this); //
    pc_new_tab.bAcc(&rcOther); // accumulates 2 arrays, irrelevant
    cout << "operator + return" << endl;
    return pc_new_tab;
}//CTable CTable::operator+ (CTable& rcOther)

CTable& CTable::operator= (CTable& rcOther) {
    this->i_table = rcOther.i_table;
    this->i_table_len = rcOther.i_table_len;
    this->s_name = rcOther.s_name;
    cout << "operator = return" << endl;
    return *this;
}//CTable& CTable::operator= (CTable& rcOther)

和主要:

int main() {
    CTable c_tab_0, c_tab_1;
    CTable c_tab_4;
    c_tab_4 = *&(c_tab_0 + c_tab_1);
    c_tab_4.vPrintTable();
    return 0;
}

我的问题:

  1. operator+在本地创建一个名为“ operator”的对象,并在最后返回其副本(“ operator_copy”)。但是,为什么在运算符=返回之后,删除了operator_copy对象,而当+返回时,除了在本地创建的CTable对象之外,没有删除任何东西?对其进行调试,我在deleting: operator_copy之后从CTable析构函数中收到消息operator = return

注意:我知道在c_tab_4中创建的内存泄漏,并且在处程序崩溃,但这只是一个例子

0 个答案:

没有答案
相关问题