c++ 为什么Foo({})调用Foo(0)而不是Foo()?

栏目: C++ · 发布时间: 7年前

内容简介:http://stackoverflow.com/questions/26788402/why-does-foo-invoke-foo0-instead-of-foo

可执行文件由clang 3.5.0和gcc 4.9.1从代码生成

#include <iostream>

struct Foo
{
   Foo() { std::cout << "Foo()" << std::endl; }
   Foo(int x) { std::cout << "Foo(int = " << x << ")" << std::endl; }
   Foo(int x, int y) { std::cout << "Foo(int = " << x << ", int = " << y << ")" << std::endl; }
};

int main()                 // Output
{                          // ---------------------
   auto a = Foo();         // Foo()
   auto b = Foo(1);        // Foo(int = 1)
   auto c = Foo(2, 3);     // Foo(int = 2, int = 3)
   auto d = Foo{};         // Foo()
   auto e = Foo{1};        // Foo(int = 1)
   auto f = Foo{2, 3};     // Foo(int = 2, int = 3)
   auto g = Foo({});       // Foo(int = 0)          <<< Why?
   auto h = Foo({1});      // Foo(int = 1)
   auto i = Foo({2, 3});   // Foo(int = 2, int = 3)
}

表现为评论.

cppreference: cpp/language/list initialization

06001

The effects of list initialization of an object of type T are:

If T is an aggregate type, aggregate initialization is performed.

Otherwise, If the braced-init-list is empty and T is a class type with a default constructor, value-initialization is performed.

06002

我得出结论,Foo({})应该调用默认构造函数.

这个bug在哪里?

默认构造函数仅适用于您使用一对大括号:

auto a = Foo();         // Foo()
auto b = Foo{};         // Foo()

Foo({})只会调用具有空列表的构造函数作为参数,copy-list-initialize任何构造函数的参数. [dcl.init] / 16:

If the destination type is a (possibly cv-qualified) class type:

— If

the initialization is direct-initialization […] constructors are considered. The applicable constructors

are enumerated (13.3.1.3), and the best one is chosen through overload

resolution (13.3).

The constructor so selected is called to

initialize the object, with the initializer expression or

expression-list
If no constructor applies, or

the overload resolution is ambiguous, the initialization is

ill-formed.

你有一个参数:空的braced-init-list.有一个列表初始化序列将{}转换为int,所以构造函数Foo(int)是通过重载分辨率来选择的.参数初始化为零,因为{}表示一个 value-intialization ,对于标量,这意味着一个 zero-initialization .

在cppreferences文档中也没有错误:对于(7)说明

7) in a functional cast expression or other direct-initialization,  with braced-init-list used as the constructor argument

这显然导致与上述引用相同的结果:使用(空)braced-init-list调用构造函数.

http://stackoverflow.com/questions/26788402/why-does-foo-invoke-foo0-instead-of-foo


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

機器,平台,群眾

機器,平台,群眾

安德魯‧麥克費(Andrew McAfee)、艾瑞克‧布林優夫森(Erik Brynjolfsson) / 李芳齡 / 天下文化 / 2017-12-27 / TWD550

★★Amazon.com商業理財Top1 ★★ 全球暢銷書《第二次機器時代》作者最新力作 兩位MIT數位頂尖科學家歷時三年時間 走訪矽谷、華府、劍橋、紐約、倫敦、舊金山等科技政經重鎮 拜會許多領域精英進行交流,結合宏觀趨勢觀察, 指出人人都應關注的三重革命 科技正以空前速度改變每個產業及每個人的生活, 你該如何做,才能保持領先? 我們生活在一個奇特的......一起来看看 《機器,平台,群眾》 这本书的介绍吧!

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具