Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

Your expectations are correct and gcc 4.7.2 does generate the default move assignment, the

vector& operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())

is invoked, just as you expected.

So, as DyP points out, it is a not yet implemented feature in Visual Studio 2012.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top