gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:27:23 29 4
gpt4 key购买 nike

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 :

[...]

T( { arg1, arg2, ... } ) (7)

[...]

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.

[...]

我的结论是 Foo({}) 应该调用默认构造函数。

错误在哪里?

最佳答案

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

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

Foo({}) 只会调用以空列表作为参数的构造函数,复制列表初始化所选构造函数的参数。 [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 as its argument(s). If no constructor applies, or the overload resolution is ambiguous, the initialization is ill-formed.

你有一个论点:空的括号初始化列表。有一个列表初始化序列将 {} 转换为 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 调用的。

关于c++ - 为什么 Foo({}) 调用 Foo(0) 而不是 Foo()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26788402/

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