lundi 31 août 2015

Why is the C++11 move operator (=) behavior different

I have tested the move Semantic in C++11. I wrote a class with a move constructor.

class DefaultConstructor
{
public:
    DefaultConstructor(std::vector<int> test) :
        m_vec(std::forward<std::vector<int>>(test))
    {

    };

    DefaultConstructor(DefaultConstructor &&def) :
        m_vec(std::forward<std::vector<int>>(def.m_vec))
    {
    }

    DefaultConstructor& operator=(DefaultConstructor&& def) {
        m_vec = std::move(def.m_vec);
        return *this;
    }

    DefaultConstructor& operator=(const DefaultConstructor&) = delete;
    DefaultConstructor(DefaultConstructor &) = delete;

    std::vector<int> m_vec;
};

I wrote a main function that use the move semantic. I understand what happend in the move semantic and it is great tool. But there is some behavior which is for me not explainable. When I call in the main function DefaultConstructor testConstructor2 = std::move(testConstructor); for me the DefaultConstructor& operator=(DefaultConstructor&& def) should called. But the Visual Studio 2015 calls the move constructor.

int main()
{
    std::vector<int> test = { 1, 2, 3, 4, 5 };
    DefaultConstructor testConstructor(std::move(test));

    DefaultConstructor testConstructor2 = std::move(testConstructor);
    DefaultConstructor &testConstructor3 = DefaultConstructor({ 6, 7, 8, 9 });
    DefaultConstructor testConstructor4 = std::move(testConstructor3);
    swapMove(testConstructor, testConstructor2);
}

Okay I thought maybe the = Move Operator is not necessary anymore. But I tried a SwapMove function. This function calls the = move Operator.

template<typename T>
void swapMove(T &a, T &b)
{
    T tmp(std::move(a));
    a = std::move(b);
    b = std::move(tmp);
}

Can someone explain what exactly is the difference betwenn the two calls? Shouldn't be the calls a = std::move(b); and DefaultConstructor testConstructor2 = std::move(testConstructor); have the same behavior?

Aucun commentaire:

Enregistrer un commentaire