带引用类成员的赋值操作符

Assignment operator with reference class member

本文关键字:赋值操作符 成员 引用      更新时间:2023-10-16

只要从我之前的问题中产生新的问题,重载赋值操作符会导致递归警告,我被合理地敦促将此作为新问题发布。我在我的类Player中有一个引用类成员,我想实现这个类的复制构造函数和赋值操作符(=)。我必须提一下,目的是函数向量的良好工作。擦除,因为在我看来,没有擦除,它就不能正常工作。我使用矢量:vector allPlayers;类Player的成员是:

class Player
{
  private:
  int ID;
  int pMoney;
  int doubleIndicator;
  int squarePosition;
  Bank& bank;
  string pName;
  Square* capturedSquare;
  multimap<string, PropertySquare*> squaresColBought;
  multimap<string, House*> housesColBuilt;
}

如果要实现赋值操作符,是否必须避免使用reference作为类成员?地图成员呢?我最终应该如何实现赋值操作符?

另一个我不知道的最重要的问题是,当我擦除保存Player的vector的迭代器时,指针类成员所指向的对象会发生什么。任何帮助吗?

c++ '引用'只能初始化,不能赋值:

int value1(1), value2(2);
int& ref1 = value1; // OK
int& ref2; // compile error: reference not initialized
int& ref3=ref1; // OK: ref3 refers to the same variable as ref1
ref1=value2; // equivalent to 'value1=value2'.
因此,包含引用的对象也只能初始化!

确实如此:如果你需要对一个类赋值,这个类不能有引用成员变量。(事实上,可以,但是赋值不能使这些成员指向另一个位置)

当你想到这个,它是有道理的:

引用概念为另一个变量定义了"别名"。混叠意味着你对引用做的任何事情,实际上都是对被引用的位置做的。当你对这个别名应用赋值时,实际上你赋值给了引用的位置。如果您能够使用赋值使引用指向不同的位置,那么引用的目的就会丢失。

如果需要后者,则应该使用指针。

当需要赋值操作符时,我会避免使用引用成员。如果您使用(智能)指针,则可以直接执行

Player &operator=(Player const &other)
{
    bankPtr = other.bankPtr;
    // copy other members
}

在当前情况下,bank = other.bank将复制other.bank的内容,而不是将this->bank指向other.bank引用的内容。

对于multimap类型的成员,它们可以毫无问题地复制,但请记住,您将获得键的"深度"副本(因为它们是string类型),但值的"浅"指针副本,因此您最终获得共享状态。您可能希望使用shared_ptr作为值

这确实是对c++设计的一个hack,但是你可以在'this'上使用placement new来做到这一点。例如

MyClass::MyClass(ReferenceType& referenceTarget):
    myReference(referenceTarget)
{}
MyClass& MyClass::operator=(const MyClass& other)
{
    new (this) MyClass(other.myReference);
    return *this;
}