简体   繁体   English

为什么默认构造函数不适用于`vector :: emplace_back`

[英]Why default constructor doesn't 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.
}

Question> Why does vector::emplace_back request explicit definition of constructor otherwise the following line doesn't work? 问题>为什么vector::emplace_back请求构造函数的显式定义,否则以下行不起作用?

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

Also, vector::emplace_back doesn't support uniform intialization. 另外, vector::emplace_back不支持统一初始化。 Does this have sth to do with the above issue? 这与上述问题有关吗?

Thank you 谢谢

std::emplace_back() takes the arguments you provide to it and perfect-forwards them to the constructor of the value_type object it is supposed to create (in your case, PersonC ). std::emplace_back()接受你提供给它的参数,并将它们完美地转发给它应该创建的value_type对象的构造函数(在你的情况下, PersonC )。

Table 101 of the C++11 Standard specifies the semantics of emplace_back() : C ++ 11 Standard的表101规定了emplace_back()的语义:

Expression : a.emplace_back(args) 表达式a.emplace_back(args)

Return type : void 返回类型void

Operational semantics: Appends an object of type T constructed with std::forward<Args>(args)... . 操作语义:追加使用std::forward<Args>(args)...构造的 T类型的对象。

There is no constructor of PersonC that accepts an int and a const char* (or anything which could be constructed from an int and a const char* , respectively), hence the error. 没有PersonC构造函数接受intconst char* (或者可以分别从intconst char*构造的任何东西),因此错误。

In case you're wondering, the only constructors that a compiler can implicitly define are the default constructor, the copy constructor, and the move constructor. 如果您想知道,编译器可以隐式定义的唯一构造函数是默认构造函数,复制构造函数和移动构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM