This is a follow up to my previous question on references within classes (Is there an elegant way to swap references in C++?). That approach received some criticism for improper use of union and its code being not portable. This time I modified the approach in order to make the code more portable. Instead of swapping references I will now illustrate assignment of references, for the sake of simplicity. The central idea is to use placement new operator for re-assigning a reference:
struct A
{
int& r_;
public:
A(int& v) : r_(v) {}
int& get() { return r_; }
void operator=(const A& a)
{
new(this)A(a.r_);
}
};
If a class need to contain more than just references as member variables, then all the references can be grouped in a base class with the corresponding assignment operator. The full example can be found here: https://ideone.com/bGcdxP. What do you think of this approach? Does it have any drawbacks that would prevent it from being used in production code?