Direct Initialization vs Copy Initialization for Primitives

谁说胖子不能爱 提交于 2019-11-28 05:50:13

问题


When initializing primitive types like int or pointers one can use either copy-initialization or direct-initialization.

int a = 10;
int b(10);

Although the latter way is preffered for objects with constructors, I don't see people using it for primitives. I understand that it is kind of "more natural" (especially for numbers) to use the '=' operator but is there anybody writing things like in real-life code:

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

Thanks.

EDIT: The question asks about coding styles and best practices rather than technical implementation.


回答1:


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.




回答2:


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.




回答3:


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())
{
}



回答4:


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.



来源:https://stackoverflow.com/questions/7091784/direct-initialization-vs-copy-initialization-for-primitives

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