简体   繁体   中英

c++ copy assignment operator for reference object variable

I give the following example to illustrate my question:

class Abc
{
public:
    int a;
    int b;
    int c;

};

class Def
{
public:
    const Abc& abc_;

    Def(const Abc& abc):abc_(abc) { }

    Def& operator = (const Def& obj)
    {
        // this->abc_(obj.abc_);
        // this->abc_ = obj.abc_;
    }
};

Here I do not know how to define the copy assignment operator. Do you have any ideas? Thanks.

references cannot be assigned to. You need something that can. A pointer would work, but they're very abusable.

How about std::reference_wrapper ?

#include <functional>

class Abc
{
public:
    int a;
    int b;
    int c;
};

class Def
{
public:
    std::reference_wrapper<const Abc> abc_;

    Def(const Abc& abc):abc_(abc) { }

    // rule of zero now supplies copy/moves for us

    // use the reference
    Abc const& get_abc() const {
      return abc_.get();
    }
};

A reference cannot be assigned. Due to this, one can only define it via placement new and copy construction:

Def& operator = (const Def& obj)
{
      this->~Def(); // destroy
      new (this) Def(obj); // copy construct in place
}

But it is really unnecesary. Just use a pointer.

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