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?
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.
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.
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 ) {} // ... };
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