Why the default constructor does not work for `vector :: emplace_back`

#include <vector> #include <string> #include <iostream> struct PersonA { int age; std::string name; PersonA(int _age, const std::string& _name) : age(_age), name(_name) {} }; struct PersonB { int age; std::string name; PersonB(int _age, const std::string&& _name): age(_age), name(_name) {} }; struct PersonC { int age; std::string name; }; int main() { std::vector<PersonA> personA; personA.emplace_back(10, "nameA"); // fine std::vector<PersonB> personB; personB.emplace_back(10, "nameB"); // fine std::vector<PersonC> personC; //personC.emplace_back(10, "nameC"); // (the implicit move constructor) not viable // (the implicit default constructor) not viable personC.emplace_back(); // UPDATE: fine. } 

Questions> Why vector::emplace_back requests an explicit constructor definition, otherwise the next line does not work?

 // why it cannot make use of the default constructor of PersonC? personC.emplace_back(10, "nameC"); 

In addition, vector::emplace_back does not support uniform rendering. Does this relate to the above problem?

thanks

+4
source share
1 answer

std::emplace_back() takes the arguments that you provide it, and perfect - sends them to the constructor of the value_type object that it must create (in your case, PersonC ).

Table 101 of the C ++ 11 standard indicates the semantics of emplace_back() :

Expression: a.emplace_back(args)

Return Type: void

Operational semantics: adds an object of type T built with std::forward<Args>(args)...

There is no PersonC constructor that accepts int and a const char* (or anything that can be built from int and a const char* , respectively), therefore, an error.

If you're interested, the only constructors that the compiler can implicitly define are the default constructor, copy constructor, and move constructor.

+6
source

Source: https://habr.com/ru/post/1489323/


All Articles