Direct Initialization vs Copy Initialization for Primitives

徘徊边缘 提交于 2019-11-29 11:40:14

Some people do this to be consistent.

Inside a template, the code could be

for (T i(0); i < 5; ++i) {
    cout << i << endl;
}

and writing it that way everywhere would make the coding style consistent.

Both are initialization using the copy constructor, even though the first looks like an assignment. It's just syntactic sugar.

You could check it easily with a class that prints out something at copy construction and something different at assignment.

And int being a primitive doesn't even come into play.

I prefer the i = 0 style, it is easier to read, and you can also use it in like this:

if (int i = some_function())
{
}

Works also fine with pointers, and all other types convertible to bool:

if (const int* p = some_function())
{
}

if (shared_ptr<const int> q = some_function())
{
}

I used to have a colleague doing so:

for (int i(0); i < 5; ++i) {
    cout << i << endl;
}

and it really pissed everyone off. It's far easier to read the code using i = 0 than i(0). Maybe not in this example but, as a general rule, it is.

Even for complex objects, I always prefer the i = 0 style, it just feels more natural for the reader and any decent compiler will optimize the generated code so there is virtually no performance penalty.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!