简体   繁体   中英

Assignment operator with reference members

Is this a valid way to create an assignment operator with members that are references?

#include <new>

struct A
{
    int &ref;
    A(int &Ref) : ref(Ref) { }
    A(const A &second) : ref(second.ref) { }
    A &operator =(const A &second)
    {
        if(this == &second)
            return *this;
        this->~A();
        new(this) A(second);
        return *this;
    }
}

It seems to compile and run fine, but with c++ tendency to surface undefined behavior when least expected, and all the people that say its impossible, I think there is some gotcha I missed. Did I miss anything?

It's syntactically correct. If the placement new throws, however, you end up with an object you can't destruct. Not to mention the disaster if someone derives from your class. Just don't do it.

The solution is simple: if the class needs to support assignment, don't use any reference members. I have a lot of classes which take reference arguments, but store them as pointers, just so the class can support assignment. Something like:

struct A
{
    int* myRef;
    A( int& ref ) : myRef( &ref ) {}
    // ...
};

Another solution is to use the reference_wrapper class ( in functional header ) :

struct A
{
    A(int& a) : a_(a) {}
    A(const A& a) : a_(a.a_) {}

    A& operator=(const A& a)
    {
        a_ = a.a_;
        return *this;
    }

    void inc() const
    {
        ++a_;
    }

    std::reference_wrapper<int>a_;

};

What you do its technically correct as far as I know, but it generates trouble. For instance, consider what happens with a derived class from A , since its assignment operator generates a new object (slicing). Can't you just turn the reference into a pointer within your class?

Besides that, copy constructors and assignment operators usually take its argument by const& .

What you do is correct, but it is not very exception safe way of writing an copy assignment operator. Also, You should consider using a pointer member rather than an reference member.

You should implement it using the Copy and Swap Idiom . It has atleast 3 advantages over your implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM