lundi 31 juillet 2017

std::move(std::array) g++ vs visual-c++

I had some problem implementing the move constructor for an element in my std::array in my project in visual studio 2013.

So I tried making a minimal example in netbeans that I compiled with g++ 5.3.0 .
Only to find that in g++ I could do what I was trying

example g++:

#include <iostream>
#include <array>

using namespace std;

struct A{
    A() = default;
    A(const A&)
    {
        cout << "copy constructed" << endl;
    }
    A(A&&)
    {
        cout << "move constructed" << endl;
    }
};

class B{
public:
    B(array<A, 2>& a)
      : m_a(std::move(a))
    {}
private:
    array<A, 2> m_a;
};

int main(){
    A foo;
    cout << "=========1===========" << endl;
    array<A, 2> a = { { foo, std::move(foo) } };
    cout << "=========2===========" << endl;
    B b(a);
    cout << "=========3===========" << endl;
    array<A, 2> a_second = std::move(a);
    return 0;
}

Output:

=========1===========
copy constructed
move constructed
=========2===========
move constructed
move constructed
=========3===========
move constructed
move constructed

When I tried the (practically) the same code in visual studio 2013 the result was different:

#include "stdafx.h"

#include <iostream>
#include <array>

using namespace std;

struct A
{
    A() = default;
    A(const A&)
    {
        cout << "copy constructed" << endl;
    }
    A(A&&)
    {
        cout << "move constructed" << endl;
    }
};

class B
{
public:
    B(array<A, 2>& a)
        : m_a(std::move(a))
    {
    }
private:
    array<A, 2> m_a;
};

int _tmain(int argc, _TCHAR* argv[])
{
    A foo;
    cout << "=========1===========" << endl;
    array<A, 2> a = { { foo, std::move(foo) } };
    cout << "=========2===========" << endl;
    B b(a);
    cout << "=========3===========" << endl;
    array<A, 2> a_second = std::move(a);
    return 0;
}

Output:

=========1===========
copy constructed
move constructed
=========2===========
copy constructed
copy constructed
=========3===========
copy constructed
copy constructed

How can I use the move constructor in visual c++ and why does visual c++ refuse to use him here?

Aucun commentaire:

Enregistrer un commentaire