Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use uniform initialization? [duplicate]

Tags:

c++

c++11

struct

In C++11 it's possible to initialize an struct using uniform initialization like below:

struct BasicStruct {
    BasicStruct (int x, double y) : x_{x}, y_{y} {}

private:
    int x_;
    double y_;
};

BasicStruct var1{5, 3.2};

Questions:

  1. When should I use this syntax BasicStruct var1{5, 3.2} instead of calling the constructor like BasicStruct var1(5, 3.2)?

  2. When should I initialize an attribute like x_{x} instead of old fashion way x_(x)?

like image 938
MBZ Avatar asked Aug 15 '13 00:08

MBZ


People also ask

What is the point of uniform initialization in C++?

Uniform Initialization in C++ The uniform initialization is a feature that permits the usage of a consistent syntax to initialize variables and objects which are ranging from primitive type to aggregates. In other words, it introduces brace-initialization that applies braces ({}) to enclose initializer values.

What is uniform C++?

uniform, a C++ code which returns a sequence of uniformly distributed pseudorandom numbers. The fundamental underlying random number generator is based on a simple, old, and limited linear congruential random number generator originally used in the IBM System 360.

How do you initialize a list in C++?

In C++11 and above, we can use the initializer lists '{...}' to initialize a list. This won't work in C++98 as standard permits list to be initialized by the constructor, not by '{...}' .


1 Answers

Use list-initialization when the list is generic and you could substitute another container, such as an array, an aggregate, or a vector, without changing its meaning much.

// "triplet" may be a struct, an array, or a std::vector,
// but it has at least single-precision floating-point values.
triplet dimensions { 5, 1.2f, static_cast< float >( M_PI ) };

If you are constructing a specific class with arguments to a specific constructor, then old-fashioned parens are more appropriate.

One unique feature of initialization with a braced-init-list is that it does not allow narrowing conversions which could cause numeric data to be lost, for example the fractional part of a floating-point number or the high bits of a long. This helps to flag (or prevent) errors resulting from substitution of e.g. a narrower array type during code refactoring.

Likewise, the other case where x{ y } is appropriate is when performing a numeric conversion that you do not with to be lossy. x( y ) will try really hard to make the conversion, even resorting to a reinterpret_cast, and should generally be avoided.

The terminology "uniform initialization" is a bit optimistic, and it does not appear in the standard. It is not appropriate for all cases. Braces generally indicate lists, so it's properly called list-initialization. And that is when it should be used.

like image 129
Potatoswatter Avatar answered Oct 10 '22 23:10

Potatoswatter