gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:11:48 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com