[英]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 withstd::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
构造函数接受int
和const char*
(或者可以分别从int
和const 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.