开发者

Direct Initialization vs Copy Initialization for Primitives

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜