c++ - Is it good habit to always initialize objects with {}? -


initializing objects new {} syntax this:

int { 123 }; 

has benefit - not declare function instead of creating variable mistake. heard should habit that. see happen:

// want create vector 5 ones in it: std::vector<int> vi{ 5, 1 }; // ups have vector 5 , 1. 

is habit then? there way avoid such problems?

frankly, subtleties of various initialization techniques make difficult 1 practice "good habit."

as mentioned in comment, scott meyers discusses brace-initialization @ length in modern effective c++. has made further comments on matter on blog, instance here , here. in second post, says explicitly thinks morass of c++ initialization vagaries bad language design.

as mentioned in 101010's answer, there benefits brace-initialization. prevention of implicit narrowing main benefit, in opinion. "most vexing parse" issue of course genuine benefit, it's paltry--it seems me in cases incorrect int a(); instead of int a; caught @ compile time.

but there @ least 2 major drawbacks:

  • in c++11 , c++14, auto deduces std::initializer_list brace-initializer. in c++17, if there's 1 element in initialization list, , = not used, auto deduces type of element; the behavior multiple elements unchanged (see second blog post linked above clearer explanation, examples.) (edit: pointed out t.c. in comment below, understanding of c++17 rules auto brace initialization still not quite right.) of these behaviors surprising , (in mine , scott meyers' opinions) annoying , perplexing.
  • 101010's third listed benefit, initialization list constructors preferred other constructors, drawback benefit. you've mentioned behavior of std::vector<int> vi{ 5, 1 }; surprising people familiar vector's old two-element constructor. scott meyers lists other examples in effective modern c++. personally, find worse auto deduction behavior (i use auto copy initialization, makes first issue easy avoid).

edit: turns out stupid compiler-implementation decisions can another reason use brace-initialization (though #undef approach more correct).


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -