Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

emplacing a POD [duplicate]

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?

like image 638
fredoverflow Avatar asked Dec 19 '12 22:12

fredoverflow


1 Answers

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.

like image 80
Joseph Mansfield Avatar answered Nov 11 '22 08:11

Joseph Mansfield