今天,我偶然发现了 these standard declarations std::vector
构造函数:
// 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() );
这两种模式有什么区别,它们的(缺点)优点是什么?
它们是严格等价的吗?编译器会从第一个生成类似于第二个的东西吗?
最佳答案
区别在于
explicit vector( const Allocator& alloc = Allocator() );
即使在使用默认参数的情况下也是显式
,而
vector() : vector( Allocator() ) {}
不是。 (第一种情况下的 explicit
是防止 Allocator
被隐式转换为 vector
所必需的。)
这意味着你可以写
std::vector<int> f() { return {}; }
或
std::vector<int> vec = {};
在第二种情况下,但不是第一种。
见 LWG issue 2193 .
关于c++ - 构造函数 : difference between defaulting and delegating a parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25694780/