Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ copy assignment operator for reference object variable

Tags:

c++

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.

like image 743
feelfree Avatar asked Sep 16 '26 20:09

feelfree


1 Answers

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();
    }
};
like image 123
Richard Hodges Avatar answered Sep 19 '26 09:09

Richard Hodges