2

Default initialization in C++11?

I am not sure which style should I use:

T o; T o{}; 

Is there difference?

3
  • I think T o; is most common. Also, do you mean T o();? Commented Dec 24, 2013 at 16:12
  • @thesquaregroot, no he doesn't. That's C++11's new initialization syntax. using parentheses results in the most vexing parse Commented Dec 24, 2013 at 16:14
  • I think there are a good minor points here. T o{}; won't work on old compilers, and it may scare some people who are out of touch. Commented Dec 24, 2013 at 16:33

1 Answer 1

7

T o; performs default initialization (in particular, it leaves non-class members uninitialized)

T o{}; performs value initialization (in particular, it zeroes out non-class members)

Sign up to request clarification or add additional context in comments.

7 Comments

What do you mean by non-class members?
@user3111311 members of non-class types (ints, pointers, arrays of such, etc)
remember {} isnt strictly better, the first is potentially faster than the second. and there is little point in setting things to zero if we are about to squash them in the next few lines.
Note that whether the value initialization zeros out built-ins and PODs can depend on whether T has a user defined default constructor or whether any of the members are initialized at the point of declaration.
@user3111311: You shouldn't "always prefer" anything, ever. Stop looking for mantras to follow: where you find them, they shall serve you poorly.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.