Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment operator with reference members

Tags:

c++

reference

Is this a valid way to create an assignment operator with members that are references?

#include <new>  struct A {     int &ref;     A(int &Ref) : ref(Ref) { }     A(const A &second) : ref(second.ref) { }     A &operator =(const A &second)     {         if(this == &second)             return *this;         this->~A();         new(this) A(second);         return *this;     } } 

It seems to compile and run fine, but with c++ tendency to surface undefined behavior when least expected, and all the people that say its impossible, I think there is some gotcha I missed. Did I miss anything?

like image 262
Dani Avatar asked Oct 26 '11 16:10

Dani


People also ask

Is ++ an assignment operator?

Assignment Operators in C/C++ Assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value.

How do you write an assignment operator?

The assignment operator is used to assign the value, variable and function to another variable. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. Example of the Assignment Operators: A = 5; // use Assignment symbol to assign 5 to the operand A.


1 Answers

It's syntactically correct. If the placement new throws, however, you end up with an object you can't destruct. Not to mention the disaster if someone derives from your class. Just don't do it.

The solution is simple: if the class needs to support assignment, don't use any reference members. I have a lot of classes which take reference arguments, but store them as pointers, just so the class can support assignment. Something like:

struct A {     int* myRef;     A( int& ref ) : myRef( &ref ) {}     // ... }; 
like image 158
James Kanze Avatar answered Oct 09 '22 21:10

James Kanze