I stumbled upon the following problem when using the checked implementation of glibcxx:
/usr/include/c++/4.8.2/debug/vector:159:error: attempt to self move assign.
Objects involved in the operation:
sequence "this" @ 0x0x1b3f088 {
type = NSt7__debug6vectorIiSaIiEEE;
}
Which I have reduced to this minimal example:
#include <vector>
#include <random>
#include <algorithm>
struct Type {
std::vector<int> ints;
};
int main() {
std::vector<Type> intVectors = {{{1}}, {{1, 2}}};
std::shuffle(intVectors.begin(), intVectors.end(), std::mt19937());
}
Tracing the problem I found that shuffle
wants to std::swap
an element with itself. As the Type
is user defined and no specialization for std::swap
has been given for it, the default one is used which creates a temporary and uses operator=(&&)
to transfer the values:
_Tp __tmp = _GLIBCXX_MOVE(__a);
__a = _GLIBCXX_MOVE(__b);
__b = _GLIBCXX_MOVE(__tmp);
As Type
does not explicitly give operator=(&&)
it is default implemented by "recursively" applying the same operation on its members.
The problem occurs on line 2 of the swap code where __a
and __b
point to the same object which results in effect in the code __a.operator=(std::move(__a))
which then triggers the error in the checked implementation of vector::operator=(&&)
.
My question is: Who's fault is this?
- Is it mine, because I should provide an implementation for
swap
that makes "self swap" aNOP
? - Is it
std::shuffle
's, because it should not try to swap an element with itself? - Is it the checked implementation's, because self-move-assigment is perfectly fine?
- Everything is correct, the checked implementation is just doing me a favor in doing this extra check (but then how to turn it off)?
I have read about shuffle requiring the iterators to be ValueSwappable. Does this extend to self-swap (which is a mere runtime problem and can not be enforced by compile-time concept checks)?
Addendum
To trigger the error more directly one could use:
#include <vector>
int main() {
std::vector<int> vectorOfInts;
vectorOfInts = std::move(vectorOfInts);
}
Of course this is quite obvious (why would you move a vector to itself?).
If you where swapping std::vector
s directly the error would not occur because of the vector class having a custom implementation of the swap function that does not use operator=(&&)
.