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);
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.
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.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With