Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I think people are starting to get annoyed at how how these are all equivalent, and the switch in a lot of books seems to be towards the third version with braces.

    int x = 0; // makes sense
    int x(0); // sure
    int x{0}; // braces?


> these are all equivalent

I'm almost positive that isn't the case. Need to find my copy of Effective Modern C++ and get back to you. It's been a while


except they are not all equal. hence why there's 3 ways to do it.

(Optimizations can change things, but per the spec, they are not the same)

the first creates a new variable with a default value and then copies 0 into it. (This is trivial with an int, but not so with a more complex type)

the second case creates x using the copy constructor

the third uses an initializer list, and works similarly to #2


> the first creates a new variable with a default value and then copies 0 into it.

No, no default constructor is invoked. In this specific example, until C++17, a temporary int object is created then x is copy constructed from it [1]. The compiler is explicitly allowed to omit the temporary+copy and directly construct from the parameter as per int x(0), but the constructor must be non-explicit.

From c++-17 on this is actually required and additionally a copy constructor is not required to exist. In practice is equivalent to #2 except for the non-explicit requirement.

Pedantic, I know, but as long as we are trying to clarify the rules is better to be clear.

[1] note: is different from default initialize then assign.


As a C++ programmer I'm more annoyed that they're not equivalent.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: