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

标签 c++ c++11

#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.
}

问题> 为什么 vector::emplace_back 要求构造函数的显式定义否则下面的行不起作用?

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

此外,vector::emplace_back 不支持统一初始化。这和上面的问题有关系吗?

谢谢

最佳答案

std::emplace_back()获取您提供给它的参数并将它们完美转发给 value_type 的构造函数它应该创建的对象(在您的情况下为 PersonC )。

C++11 标准的表 101 指定了 emplace_back() 的语义:

Expression: a.emplace_back(args)

Return type: void

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

PersonC 没有构造函数接受 int和一个 const char* (或任何可以分别由 intconst char* 构造的东西),因此出现错误。

如果您想知道,编译器可以隐式定义的唯一构造函数是默认构造函数、复制构造函数和移动构造函数。

关于c++ - 为什么默认构造函数不适用于 `vector::emplace_back`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17431332/

相关文章:

c++ - 在类中存储对对象的 const 引用

c++ - 以下 C++ 程序无法编译并显示各种错误

c++ - 使用序列优雅地初始化静态(成员)数组

c++ - 为什么cout指针可以改变数据

c++ - Arduino LCD仅显示第1行的前16个字符和第2行的41到46个字符

c++ - std::multimap<std::chrono::milliseconds, T>::rbegin 指向 MSVS-13 中的 end()?

c++ - 为什么允许函数声明中的前向声明?

c++ - 字段 'buffer_' 的类型不完整 'boost::array<char , 4096ul>'

c++11 - 为什么在 C++0x 中没有为 std::weak_ptr 定义 std::hash ?

c++ - 是否有 Windows 驱动程序函数相当于 Windows 文件 api SeFileAttributes