In the following code:
class MyClass
{
public:
vector<int> v;
};
MyClass f()
{
MyClass x;
x.v.resize(10);
for (int i = 0; i < 10; i++)
{
x.v[i] = i;
}
return x;
}
void g()
{
MyClass x;
x = f(); // Copy assignment is called for vector<int>
}
compiled with Visual C++ 2012 in line x = f()
I assumed that move assignment would be called for the vector. Instead I can see that the copy assignment is called. There are no copy/move assignment/constructor defined in the class, so I was hoping that the compiler would generate the default move assignment. If I use plain vector instead of MyClass
the move assignment works fine. Is there something wrong with this code? Am I missing something?
As MSDN states, VS2012 does not yet implicitly declare&define move-ctors and -assignment-ops:
"Rvalue references v3.0" adds new rules to automatically generate move constructors and move assignment operators under certain conditions. However, this is not implemented in Visual C++ in Visual Studio 2012, due to time and resource constraints.
Therefore, you'll have to provide own, user-defined move-ctors and -assignment-ops (maybe = default
suffices).
That said, and as Ali pointed out, x = f()
should indeed call the move-assignment-op of MyClass
, invoking the move-assignment-op of vector
.