构造函数:默认和委派参数之间的区别 [英] Constructors : difference between defaulting and delegating a parameter

查看:92
本文介绍了构造函数:默认和委派参数之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我偶然发现了<$ 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 Allocators 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆