[英]Trying to construct a vector from initializer list using std::make_unique()
I struggle to understand the code below.我很难理解下面的代码。 Why can
v2
be constructed from an initializer list, but v3
fails?为什么
v2
可以从初始化列表构造,但v3
失败了?
#include <vector>
#include <memory>
int main()
{
auto v1 = std::make_unique<std::vector<int>>(std::vector<int>({1,2,3,4,5})); // works
auto x = {1,2,3,4,5};
auto v2 = std::make_unique<std::vector<int>>(x); // works
//auto v3 = std::make_unique<std::vector<int>>({1,2,3,4,5}); // fails
}
Can someone explain, or point me to a resource that clarifies this behaviour?有人可以解释或指出可以澄清此行为的资源吗?
Thanks for pointing me to the answer, @joergbrech.感谢您指出我的答案,@joergbrech。
Paraphrasing the answer: the reason is a subtle difference between auto type deduction and template type deduction:解释一下答案:原因是自动类型推导和模板类型推导之间存在细微差别:
From "Effective Modern C++" by Scott Meyers:来自 Scott Meyers 的“Effective Modern C++”:
auto
type deduction is usually the same as template type deduction, butauto
type deduction assumes that a braced initializer represents astd::initializer_list
, and template type deduction doesn't.auto
类型推导通常与模板类型推导相同,但auto
类型推导假定大括号初始化程序表示std::initializer_list
,而模板类型推导则不然。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.