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

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

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

Initializing objects with new {} syntax like this:

int a { 123 };

has benefit - you would not declare a function instead of creating a variable by mistake. I even heard that it should be habit to always do that. But see what could happen:

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

Is this good habit then? Is there a way to avoid such problems?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Initializing objects with list initialization should be preferred wherever applicable, because:

  1. Among other benefits list-initialization limits the allowed implicit narrowing conversions.

    In particular it prohibits:

    • conversion from a floating-point type to an integer type
    • conversion from a long double to double or to float and conversion from double to float, except where the source is a constant expression and overflow does not occur.
    • conversion from an integer type to a floating-point type, except where the source is a constant expression whose value can be stored exactly in the target type.
    • conversion from integer or unscoped enumeration type to integer type that cannot represent all values of the original, except where source is a constant expression whose value can be stored exactly in the target type.
  2. Another benefit is that is immune to most vexing parse.
  3. Also, initialization list constructors are preferred over other available constructors, except for the default.
  4. Also, they're widely available, all STL containers have initialization list constructors.

Now concerning your example, I would say with knowledge comes power. There's a specific constructor for making a vector of 5 ones (i.e., std::vector<int> vi( 5, 1);).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...