Possible Duplicate:
C++11 emplace_back on vector<struct>?
Is emplacement possible with PODs? It does not seem to work in Visual Studio 2012:
struct X
{
int a;
int b;
};
void whatever()
{
std::vector<X> xs;
X x = {1, 2};
// okay
xs.push_back(x);
// okay
xs.emplace_back(x);
//error C2661: 'X::X': error C2661: no overloaded function takes 2 arguments
xs.emplace_back(1, 2);
}
Is this just a shortcoming of Visual Studio 2012, or does emplacing a POD simply not work in C++11?
There is no constructor X::X(int,int)
, which is what your call to emplace_back
would use to construct the X
object. Containers use allocator_traits<A>::construct(allocator, p, args)
to construct objects, where p
is a pointer to some allocated space and args
are the arguments passed to the constructor. This is used by emplace_back
. This construct
function calls ::new((void*)p) T(std::forward<Args>(args)...)
, so it doesn't use uniform initialization.
xs.emplace_back({1, 2})
will also be an error, despite the fact that an aggregate can be constructed with list-initialization. That's because a brace-enclosed initializer list cannot be forwarded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With