Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector emplace_back() for non copy constructible objects

Tags:

c++

c++11

vector

Considering this quote from en.cppreference.com regarding std::vector::emplace_back

"Appends a new element to the end of the container. The element is constructed in-place, i.e. no copy or move operations are performed. The constructor of the element is called with exactly the same arguments that are supplied to the function."

and following sample:

#include <vector>
struct A
{
    A(int){}
    A(A const&) = delete;
};

int main()
{
    std::vector<A> vec;
    vec.emplace_back(1);

    return 0;
}

On line vec.emplace_back(1); Visual Studio 2013/GCC report:

error C2280: 'A::A(const A &)' : attempting to reference a deleted function

error: use of deleted function ‘A::A(const A&)’

Is the error correct? Can you please explain me why?

like image 909
Mircea Ispas Avatar asked Apr 10 '14 13:04

Mircea Ispas


1 Answers

C++11 23.2.1 Table 101 states:

Expression: a.emplace_back(args)

Return type: void

Operation semantics: Appends an object of type T constructed with std::forward<Args>(args).... Requires: T shall be EmplaceConstructible into X from args. For vector, T shall also be MoveInsertable into X.

Your A does not fulfill the MoveInsertable requirement, since you do not have a move constructor, and only have a deleted copy constructor. With a container other than std::vector, it works.

like image 83
Angew is no longer proud of SO Avatar answered Oct 02 '22 13:10

Angew is no longer proud of SO