c++ - 构造函数 : difference between defaulting and delegating a parameter

标签 c++ std c++14

今天,我偶然发现了 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/

相关文章:

c++ - 创建 is_primitive 或 is_inheritable 模板

c++ - 包装接收纯右值的函数时省略复制/移动

c++ - 什么是 'extern inline' 函数以及何时使用?

c++ - Qt:类中变量的默认值

c# - 将 ADODB::Recordset^ 转换为 _RecordsetPtr

c++ - 将 int64_t 转换为 time_duration

c++ - 在 std::for_each 中返回 std::move(f)

c++ - Qt 测试当前对象/小部件是否存在

c++ - 当 std::fstream 都移动一个指针时,为什么它们存在eekp/seekg?

c++ - Microsoft Integer Literal Extensions——记录在哪里?