Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...