我似乎想不出也找不到以下代码的理由:
根据使用的构造方法(我知道C++11中上述第二个构造函数已经被弃用,可能是因为这个改变,但我仍然无法理解为什么会这样。我唯一能看到这种行为的好处是,您可以使用特定值初始化容器并仅需要一对大括号;
我承认我可能漏掉了什么,但我不确定具体是什么。请注意,我只是以
我无法为以下代码找到合理的解释:
std::vector<int> a{1,2} // calls (7)
std::vector<int> a(1,2) // calls (2)
// constructors from http://en.cppreference.com/w/cpp/container/vector/vector
vector( std::initializer_list<T> init,
const Allocator& alloc = Allocator() ); // (7)
explicit vector( size_type count,
const T& value = T(),
const Allocator& alloc = Allocator()); // (2)
根据使用的构造方法(
{}
vs ()
),不同的函数被调用,这对我来说似乎非常违反直觉。为什么std::initializer_list
比其他完全匹配给定参数的函数更受欢迎呢?std::vector<int> a{1,2}
与std::vector<int> a{{1,2}}
相比。但至少对我来说,这肯定不能抵消这种行为所带来的模糊性和重载分辨率的变化。根据Scott Meyers在Effective Modern C++中的说法,std::make_unique
和std::make_shared
需要在其接口中明确声明使用哪种构造形式(因为涉及到重载分辨率)。这对我来说似乎很荒谬。我承认我可能漏掉了什么,但我不确定具体是什么。请注意,我只是以
std::vector
为例,我询问的是这个特性的一般情况。
std::vector<int> a{1,2,3};
,std::vector<int> a{1,2,3,4};
,std::vector<int> a{1,2,3,4,5};
都调用初始化列表构造函数,但std::vector<int> a{1,2};
却没有,那么会感到同样奇怪。 - T.C.std::vector<int> a{{1,2,3}}
而不是优先考虑std::initializer_list
构造函数。 - user1520427