定义运算符重载时擦除向量的对象元素时出错

sol*_*ito 1 c++ vector compiler-bug

在下面的简单示例程序中,我有一个t_cell用 5 个元素初始化的对象向量。我还有一个整数测试向量。

#include <iostream>
#include <iomanip>
#include <vector>

using namespace std;

class t_cell {
    public:
        int id;

    t_cell operator = ( const t_cell &rhs_cell ){
        t_cell lhs_cell;
        lhs_cell.id = rhs_cell.id;
        return lhs_cell;
    }
};


int main(){

    std::vector<int   > test ( 5 );
    std::vector<t_cell> cells( 5 );

    for( size_t icell=0; icell < cells.size(); icell++ ){
        test [icell]    = icell;
        cells[icell].id = icell;
    }

    for( size_t icell=0; icell < cells.size(); icell++ ){
        cout << "before =" << icell << test [icell] << cells[icell].id << endl;
    }
    cout << endl;

    // Erase
    cells.erase( cells.begin() + 3 );
    test .erase( test .begin() + 3 );

    for( size_t icell=0; icell < cells.size(); icell++ ){
        cout << "after  =" << icell << cells[icell].id << test [icell] << endl;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

擦除元素适用于整数向量,但不适用于对象向量:

before =000
before =111
before =222
before =333
before =444

after  =000
after  =111
after  =222
after  =334
Run Code Online (Sandbox Code Playgroud)

循环索引表明向量的大小已减小(现在仅从 0 减少到 3)。但是,id第三个元素的 没有被正确擦除。

我发现问题来自运算符重载定义。删除按预期工作:

before =000
before =111
before =222
before =333
before =444

after  =000
after  =111
after  =222
after  =344
Run Code Online (Sandbox Code Playgroud)

GCC 8.3.1 和 10.1.0 产生相同的行为。我编译了没有标志的代码。

cdh*_*wie 6

的目的operator=是更改*this以匹配操作数的状态,然后返回对 的引用*this,但这不是您要做的——相反,您正在创建一个值并返回它。调用者会立即丢弃返回值,因此调用运算符不会对程序状态产生任何可观察到的影响。

将代码更改为 mutate*this并返回对自身的引用:

t_cell & operator = ( const t_cell &rhs_cell ){
    id = rhs_cell.id;
    return *this;
}
Run Code Online (Sandbox Code Playgroud)

当然,在这种情况下,您的类是隐式可复制的,因为所有成员都是可复制的。你可以简单地不定义operator=,编译器会为你生成一个合适的,它和我上面展示的运算符做的完全一样。