Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying a C++ class with a member variable of reference type

Tags:

c++

I've a class which stores a reference to its parent, the reference is passed in the constructor. If I try to copy an instance I get an error "error C2582: 'operator =' function is unavailable" presumably down to the reference being non-assignable.

Is there a way around this, or do I just change the variable to pointer instead of reference?

e.g (over-simplified but I think has the key points):

class MyClass
{
public:
 MyClass(OtherClass &parent) : parent(parent) {}
private:
 OtherClass &parent;
};

MyClass obj(*this);
.
.
.
obj = MyClass(*this);
like image 961
Mr. Boy Avatar asked Oct 01 '10 16:10

Mr. Boy


People also ask

Can you copy a reference C++?

C++ gives you the choice: use the assignment operator to copy the value (copy/value semantics), or use a pointer-copy to copy a pointer (reference semantics). C++ allows you to override the assignment operator to do anything your heart desires, however the default (and most common) choice is to copy the value.

How do you reference a class member from within a class?

The members of a class are referenced (accessed) by using the object of the class followed by the dot (membership) operator and the name of the member. The members of a class are referenced (accessed) by using the object of the class followed by the dot (membership) operator and the name of the member.

How do you initialize a reference member variable in C++?

An rvalue reference can be initialized with an lvalue in the following contexts: A function lvalue. A temporary converted from an lvalue. An rvalue result of a conversion function for an lvalue object that is of a class type.

Why do you have to pass the argument to a copy constructor as a reference?

It is necessary to pass object as reference and not by value because if you pass it by value its copy is constructed using the copy constructor. This means the copy constructor would call itself to make copy. This process will go on until the compiler runs out of memory.


2 Answers

There is a way to do it and still use a reference, use a reference_wrapper. So

    T& member;

becomes

    std::reference_wrapper<T> member;

Reference wrappers are basically just re-assignable references.

like image 62
Tiedye Avatar answered Oct 17 '22 14:10

Tiedye


I don't recommend this at all

but if you are really gung ho about doing this:

#include <new>

MyClass::MyClass(const MyClass &rhs): parent(rhs.parent)
{
}

MyClass &MyClass::operator=(const MyClass &rhs)
{
    if (this!=&rhs)
    {
        this->~MyClass();
        new (this) MyClass(rhs);
    }

    return *this;
}
like image 32
MSN Avatar answered Oct 17 '22 13:10

MSN