Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 构造函数:默认和委托参数之间的区别_C++_Std_C++14 - Fatal编程技术网

C++ 构造函数:默认和委托参数之间的区别

C++ 构造函数:默认和委托参数之间的区别,c++,std,c++14,C++,Std,C++14,今天,我偶然发现了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+

今天,我偶然发现了
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() );
这两种模式的区别是什么?它们的(dis)优势是什么?
它们是严格等价的吗?编译器从第一个生成类似于第二个的东西吗?

区别在于

explicit vector( const Allocator& alloc = Allocator() );
是显式的,即使在使用默认参数的情况下也是如此,而

vector() : vector( Allocator() ) {}
事实并非如此。(第一种情况下的
显式
是防止
分配器
隐式转换为
向量
所必需的)

这意味着你可以写作

std::vector<int> f() { return {}; }
std::vector f(){return{};}

std::vector vec={};
在第二种情况下,但不是第一种情况


请参阅。

如果删除显式关键字,我假设分配器可以隐式转换为向量?哦,这比我在阅读问题时预期的有趣得多。如果我理解正确,这意味着任何具有非显式默认构造函数的类型都可以“从
{}
构造”,也就是说,有点像“虚无元素”。我同意这里的@LightnessRacesinOrbit,这比预期的有趣多了。@Alex我不确定你所说的“void元素”是什么意思;您将获得一个默认的构造对象。完全正常。不同之处在于,您可以从
{}
开始初始化,而不必显式地编写
vector()
或类似的内容。@LightnessRacesinOrbit:如果不清楚,请原谅:我指的是类似“零元素”的内容。与空容器或字符串、数字零、空指针等类似,这在模板上下文中可能很有用。另外,能够为任何空容器编写
{}
也是非常有用的。您是指标准本身规定的这些标准库容器成员函数的签名,还是指某些特定实现的代码?@LightnessRacesinOrbit我指的是前者:我假设这些函数的签名是标准的(en.cppreference.com说标准有一个变化——“自C++14以来”)@LightnessRacesinOrbit我真的不明白该编辑什么;“STL”错了吗?对我来说,它是使用模板的标准库的一部分(因此是标准的“模板”库)。还是别的?经过一番研究,我明白你的意思了。然而,“stdlib”标记似乎自动更改为“std”,这也是关于Ruby的,并且与“std”标记相比,关注者和问题明显减少。很容易误导,没关系;没有找到cppreference.com的链接。这足以表明您所谈论的是标准签名,而不是一些不符合标准的实现代码。
std::vector<int> vec = {};