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 following 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 can see, adding noexcept
did not help here (and besides, I don't think that the reasons a resize causes copies apply to initialization).
If I instead do the following:
std::vector<A> v;
v.push_back(A());
I don't get copies.
Tested with GCC 5.4 and Clang 3.8.