构造函数:默认和委派参数之间的区别 [英] Constructors : difference between defaulting and delegating a parameter
问题描述
今天,我偶然发现了<$ c的这些标准声明 $ c> std :: vector 构造函数:
Today, I stumbled upon these standard declarations of std::vector
constructors :
// until C++14
explicit vector( const Allocator& alloc = Allocator() );
// since C++14
vector() : vector( Allocator() ) {}
explicit vector( const Allocator& alloc );
在大多数标准容器中都可以看到这种变化。稍有不同的示例是 std :: set
:
This change can be seen in most of standard containers. A slightly different exemple is 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() );
两种模式之间有什么区别,它们的(缺点)有什么优点?
它们严格相等吗-编译器会从第一个生成与第二个类似的东西吗?
What is the difference between the two patterns and what are their (dis)advantages ?
Are they strictly equivalent - does the compiler generate something similar to the second from the first ?
推荐答案
explicit vector( const Allocator& alloc = Allocator() );
是显式的
使用默认参数,而
vector() : vector( Allocator() ) {}
不是。 (在第一种情况下,显式
对于防止 Allocator
隐式转换为 vector
。)
is not. (The explicit
in the first case is necessary to prevent Allocator
s from being implicitly convertible to a vector
.)
这意味着您可以编写
std::vector<int> f() { return {}; }
或
std::vector<int> vec = {};
在第二种情况下,但不是第一种。
in the second case but not the first.
请参见 LWG问题2193 。
这篇关于构造函数:默认和委派参数之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!