mercredi 26 octobre 2016

Expected move on std::vector constructed in place but copy encountered instead

Why is the following code calling a's copy constructors?

class a {
public:
    a(int x) : x_(x) { std::cout << "a constructor" << std::endl; }
    a(a&& a_) { std::cout << "a move constructor" << std::endl; }
    a(const a& a_) { std::cout << "a copy constructor" << std::endl; }

private:
    int x_;
};

class b {
public:
    b(std::vector<a>&& v) : v_(std::move(v)) {}

private:
    std::vector<a> v_;
};

int main() {
    b s({2, 3, 4, 5, 6});
}

The output is the following:

a constructor
a constructor
a constructor
a constructor
a constructor
a copy constructor
a copy constructor
a copy constructor
a copy constructor
a copy constructor

I was expecting no copy since the vector is created in place and passed as a rvalue reference and after that moved. What's actually happening?

Aucun commentaire:

Enregistrer un commentaire