今天,我偶然发现了std::vector
构造函数的these standard declarations:
// until C++14
explicit vector( const Allocator& alloc = Allocator() );
// since C++14
vector() : vector( Allocator() ) {}
explicit vector( const Allocator& alloc );
在大多数标准容器中都可以看到这种变化。一个稍有不同的例子是std::set
:
// until C++14
explicit set( const Compare& comp = Compare(),
const Allocator& alloc = Allocator() );
// since C++14
set() : set( Compare() ) {}
explicit set( const Compare& comp,
const Allocator& alloc = Allocator() );
这两种模式之间的区别是什么,它们的(不)优点是什么?
它们是严格等价的吗-编译器是否从第一个生成类似于第二个的东西?
发布于 2014-09-06 06:28:45
区别在于
explicit vector( const Allocator& alloc = Allocator() );
即使在使用默认参数的情况下也是explicit
,而
vector() : vector( Allocator() ) {}
不是。(第一种情况下的explicit
是防止Allocator
s隐式转换为vector
所必需的。)
这意味着你可以写
std::vector<int> f() { return {}; }
或
std::vector<int> vec = {};
在第二种情况下,但不是第一种情况。
https://stackoverflow.com/questions/25694780
复制相似问题