java构造函数后面大括号,用大括号而不是括号调用构造函数

I recently realized that in C++11 we can call a delegating initializer-list constructor like

Foo() : Foo{42} // delegate to Foo(initializer_list<>)

Is this syntax correct? It seems to be, although I would have expected to always use parentheses when calling a function, like Foo({42}). The example code below compiles fine in both clang++ and g++

#include

#include

struct Foo

{

Foo() : Foo{42} // I would have expected invalid syntax, use Foo({42})

{

std::cout << "Foo()... delegating constructor\n";

}

Foo(std::initializer_list)

{

std::cout << "Foo(initializer_list)\n";

}

};

int main()

{

Foo foo;

}

I am well aware of uniform initialization, like declaring objects using { }, but did not know we can also call constructors. We cannot call functions though, the following doesn't compile:

#include

void f(std::initializer_list){}

int main()

{

f{5}; // compile time error, must use f({5})

}

So, to summarize, my question is the following: are there special rules when delegating constructors, that allow for calling a init-list constructor using only braces, like Foo{something}?

解决方案

Yes, a mem-initializer such as Foo{42} can contain either a parenthesized expression-list or a braced-init-list. This is the case regardless of whether the mem-initializer-id denotes the constructor's class, a base class, or a member: that is, both when the constructor delegates and when it does not. See the grammar in [class.base.init].

Furthermore, the standard specifies ([class.base.init]/7 in C++14) that the initialization by the expression-list or braced-init-list occurs according to the usual rules of initialization. Therefore if the initializer is a braced-init-list then std::initializer_list constructors will be favoured in overload resolution.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值