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, autodeducesstd::initializer_listbrace-initializer. in c++17, if there's 1 element in initialization list, ,=not used,autodeduces 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 ofc++17rulesautobrace 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 familiarvector's old two-element constructor. scott meyers lists other examples in effective modern c++. personally, find worseautodeduction behavior (i useautocopy 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
Post a Comment