Assignment operator with reference class member

前端 未结 3 1616
一向
一向 2021-01-01 13:24

As long as new issues are growing out of my previous question Overloaded assignment operator causes warning about recursion, I was legitimately urged to post this as new one

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-01 14:27

    It is really a hack over c++ design, but you can use placement new on 'this' to do that. I.e.

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

提交回复
热议问题