问题描述
我已经习惯使用如下所示的直接列表初始化来编写代码,因为它更有效,而且对于防止隐式缩小:
I've come into the habit of writing code with direct-list-initialization like below as it's more effective and it's very useful to prevent implicit narrowing:
int i {0};
string s {""};
char c {'a'};
bool b {false};
auto num {100}; // But this??
但是当涉及到自动说明符时,我听说这样写它被认为是不好的或者不是首选,那为什么呢?
But when it comes to the auto specifier, I have heard it is considered bad or not preferred to write it like that, why is that?
推荐答案
以下是使用该语法失败的示例:
Here's an example of where using that syntax fails:
struct Foo{};
void eatFoo (const Foo& f){}
int main() {
Foo a;
auto b{a};
eatFoo(b);
}
您可能希望这没问题:b
应该是Foo
,并传递给eatFoo
.不幸的是,这导致以下编译器错误:
You might expect this to be fine: b
should be a Foo
and be passed to eatFoo
. Unfortunately, this results in the following compiler error:
prog.cpp:11:10: error: invalid initialization of reference of type 'const Foo&' from expression of type 'std::initializer_list<Foo>'
eatFoo(b);
如您所见,b
实际上是std::initializer_list<Foo>
类型.在这种情况下,当然不是我们想要的.如果我们将其更改为auto b = a
,则可以正常工作.然后,如果我们仍然想使用auto
,但要明确声明类型,则可以将其更改为auto b = Foo{a}
,然后让编译器删除该副本.
As you can see, b
is actually of type std::initializer_list<Foo>
. Certainly not what we want in this case. If we change it to auto b = a
, this works fine. Then if we want to still use auto
, but explicitly state the type, we can change it to auto b = Foo{a}
and let the compiler elide the copy.
这篇关于为什么使用auto的直接列表初始化被认为是不好的或不受欢迎的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!