lundi 17 juillet 2017

Why does std::vector enforces copy on initialization?

I have a copy/move probing class:

#include <iostream>

struct A
{
    A()
    {
        std::cout << "Creating A" << std::endl;
    }

    ~A() noexcept
    {
        std::cout << "Deleting A" << std::endl;
    }

    A(const A &)
    {
        std::cout << "Copying A" << std::endl;
    }

    A(A &&) noexcept
    {
        std::cout << "Moving A" << std::endl;
    }

    A &operator=(const A &)
    {
        std::cout << "Copy-assigning A" << std::endl;
        return *this;
    }

    A &operator=(A &&) noexcept
    {
        std::cout << "Move-assigning A" << std::endl;
        return *this;
    }
};

And I have found that running:

#include <vector>

int main(int, char **)
{
    std::vector<A> v { A() };
}

Produces the output:

Creating A
Copying A
Deleting A
Deleting A

Why won't the initialization just move the objects? I know that std::vector may create undesired copies on resize, but as you see adding noexcept did not help here (and besides I don't think the reasons why resizing may cause copies apply on initialization).

Doing instead:

std::vector<A> v;
v.push_back(A());

Does not cause copies.

Tested with GCC 5.4 and Clang 3.8.

Aucun commentaire:

Enregistrer un commentaire