c++ - Operator= 除非对象已经初始化,否则重载不起作用

标签 c++ operator-overloading operators

我有一个叫做游戏的类,这是它的 operator=: 的代码

Game& Game::operator=(const Game &other){
if(this==&other){
    return *this;
}else{
    for(unsigned i=0;i<other.players.size();i=i+1){
        Player* copy;
        int str= other.players.at(i)->getStr();
        if(str==1)
            copy = new PlayerType1(dynamic_cast<const PlayerType1&>(*other.players.at(i)));
        if(str==2)
            copy = new PlayerType2(dynamic_cast<const PlayerType2&>(*other.players.at(i)));
        if(str==3)
            copy = new PlayerType3(dynamic_cast<const PlayerType3&>(*other.players.at(i)));
        if(str==4)
            copy = new PlayerType4(dynamic_cast<const PlayerType4&>(*other.players.at(i)));
        players.push_back(copy);
    }
    winners = other.winners;
    state = vector<string>(other.state);
    deck = Deck(other.deck);
    verbal = other.verbal;
    highestNum = other.highestNum;
    turnNum = other.turnNum;
    currPlayer = other.currPlayer;
    lastAsker = other.lastAsker;
    lastAskee = other.lastAskee;
    lastAskedCard = other.lastAskedCard;
    return *this;
}

我尝试在这里调用它:

char* cf= "../src/config1.txt";
Game* game = new Game(cf);
game->init();
Game game2=*game;
game->play();
game2.printState();

在这种情况下,我的 operator= 将不会被使用。 但是如果 game2 已经初始化,例如这里:

Game* game = new Game(cf);
game->init();
Game game2=*(new Game());
game2=*game;
game->play();
game2.printState();

知道可能是什么问题吗?

最佳答案

在第一种情况下,copy elision避免调用赋值运算符,支持复制构造函数。

在第二种情况下,对象已经构建,因此必须调用赋值运算符。

结论是您必须实现所有 3 个运算符:析构函数、赋值和复制(也称为 rule of three),否则您可能会出现不可预测的行为,具体取决于编译器。

避免以不一致的方式实现它们的最佳方法是使用 copy & swap idiom

关于c++ - Operator= 除非对象已经初始化,否则重载不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40821437/

相关文章:

c++ - 尝试使用winbgim显示文本时出现编译器错误

c++ - (错误 C2678)错误 : No operator "<<" matches these operands

scala - 什么是 SBT := operator in build. sbt?

c++ - 如何重载 operator< 以将对象放入集合中

c++ - 隔离C库类(C++代码)

c++ - WinAPI:是否需要在可执行内存映射文件上调用 FlushInstructionCache?

c++ - `void operator=(T&&)` 和 `T& operator=(T&&)` 有什么区别?

php - 用PHP中的@运算符抑制错误

c++ - 任何在 64 位机器上使用 8 个字节作为 int 数据类型大小的 C/C++ 编译器

c++ - 包装数组的类的转换与下标运算符重载