The problem I am trying to address arises with making containers such as an std::vector
of objects that contain reference and const data members:
struct Foo;
struct Bar {
Bar (Foo & foo, int num) : foo_reference(foo), number(num) {}
private:
Foo & foo_reference;
const int number;
// Mutable member data elided
};
struct Baz {
std::vector<Bar> bar_vector;
};
This won't work as-is because the default assignment operator for class Foo
can't be built due to the reference member foo_reference
and const member number
.
One solution is to change that foo_reference
to a pointer and get rid of the const
keyword. This however loses the advantages of references over pointers, and that const
member really should be const
. They are private members, so the only thing that can do harm is my own code, but I have shot myself in the foot (or higher) with my own code.
I've seen solutions to this problem on the web in the form of swap
methods that appear to be chock full of undefined behavior based on the wonders of reinterpret_cast
and const_cast
. It happens that those techniques do appear to work on my computer. Today. With one particular version of one particular compiler. Tomorrow, or with a different compiler? Who knows. I am not going to use a solution that relies on undefined behavior.
Related answers on stackoverflow:
- Does it make sense to implement the copy-assignment operator in a class with all const data members?
The first answer has the amusing line "If that one is immutable, your screwed." - Swap method with const members
The first answer doesn't really apply here, and the second is a bit of a kludge.
So is there a way to write a swap
method / copy constructor for such a class that does not invoke undefined behavior, or am I just screwed?
Edit
Just to make it clear, I already am quite aware of this solution:
struct Bar {
Bar (Foo & foo, int num) : foo_ptr(&foo), number(num) {}
private:
Foo * foo_ptr;
int number;
// Mutable member data elided
};
This explicitly eliminates the const
ness of number
and the eliminates the implied const
ness of foo_reference
. This is not the solution I am after. If this is the only non-UB solution, so be it. I am also quite aware of this solution:
void swap (Bar & first, Bar & second) {
char temp[sizeof(Bar)];
std::memcpy (temp, &first, sizeof(Bar));
std::memcpy (&first, &second, sizeof(Bar));
std::memcpy (&second, temp, sizeof(Bar));
}
and then writing the assignment operator using copy-and-swap. This gets around the reference and const problems, but is it UB? (At least it doesn't use reinterpret_cast
and const_cast
.) Some of the elided mutable data are objects that contain std::vector
s, so I don't know if a shallow copy like this will work here.
const
- and reference-members benoncopyable
anyways? Atleast that's what I learned. That said,move
-swap should work just fine, but that's not C++03. – Conny