feelfree
feelfree

Reputation: 11763

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.

Upvotes: 3

Views: 1255

Answers (2)

Richard Hodges
Richard Hodges

Reputation: 69912

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();
    }
};

Upvotes: 8

n. m. could be an AI
n. m. could be an AI

Reputation: 120079

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.

Upvotes: 4

Related Questions