ChatGPT解决这个技术问题 Extra ChatGPT

What are the advantages of list initialization (using curly braces)?

MyClass a1 {a};     // clearer and less error-prone than the other three
MyClass a2 = {a};
MyClass a3 = a;
MyClass a4(a);

Why?

Wouldn't fit the comment box ;). Anyway, to quote from the linked article: "...the main reasons to declare variables using auto are for correctness, performance, maintainability, and robustness—and, yes, convenience...".
That's true, it is convenient, but it reduces readability in my opinion - I like to see what type an object is when reading code. If you are 100% sure what type the object is, why use auto? And if you use list initialization (read my answer), you can be sure that it is always correct.
@Oleksiy: std::map<std::string, std::vector<std::string>>::const_iterator would like a word with you.
@Oleksiy I recommend reading this GotW.
@doc I'd say using MyContainer = std::map<std::string, std::vector<std::string>>; is even better (especially as you can template it!)

A
Augustin

Basically copying and pasting from Bjarne Stroustrup's "The C++ Programming Language 4th Edition":

List initialization does not allow narrowing (§iso.8.5.4). That is:

An integer cannot be converted to another integer that cannot hold its value. For example, char to int is allowed, but not int to char.

A floating-point value cannot be converted to another floating-point type that cannot hold its value. For example, float to double is allowed, but not double to float.

A floating-point value cannot be converted to an integer type.

An integer value cannot be converted to a floating-point type.

Example:

void fun(double val, int val2) {

    int x2 = val;    // if val == 7.9, x2 becomes 7 (bad)

    char c2 = val2;  // if val2 == 1025, c2 becomes 1 (bad)

    int x3 {val};    // error: possible truncation (good)

    char c3 {val2};  // error: possible narrowing (good)

    char c4 {24};    // OK: 24 can be represented exactly as a char (good)

    char c5 {264};   // error (assuming 8-bit chars): 264 cannot be 
                     // represented as a char (good)

    int x4 {2.0};    // error: no double to int value conversion (good)

}

The only situation where = is preferred over {} is when using auto keyword to get the type determined by the initializer.

Example:

auto z1 {99};   // z1 is an int
auto z2 = {99}; // z2 is std::initializer_list<int>
auto z3 = 99;   // z3 is an int

Conclusion

Prefer {} initialization over alternatives unless you have a strong reason not to.


There is also the fact that using () can be parsed as a function declaration. It is confusing and inconsistent that you can say T t(x,y,z); but not T t(). And sometimes, you certain x, you can't even say T t(x);.
I strongly disagree with this answer; braced initialization becomes a complete mess when you have types with a ctor accepting a std::initializer_list. RedXIII mentions this issue (and just brushes it off), whereas you completely ignore it. A(5,4) and A{5,4} can call completely different functions, and this is an important thing to know. It can even result in calls that seem unintuitive. Saying that you should prefer {} by default will lead to people misunderstanding what's going on. This isn't your fault, though. I personally think it's an extremely poorly thought out feature.
@user1520427 That's why there's the "unless you have a strong reason not to" part.
Although this question is old it has quite a few hit thus I'm adding this here just for reference ( I haven't seen it anywhere else in the page ). From C++14 with the new Rules for auto deduction from braced-init-list it is now possible to write auto var{ 5 } and it will be deduced as int no more as std::initializer_list<int>.
Haha, from all the comments it's still not clear what to do. What is clear is, that the C++ specification is a mess!
l
laike9m

There are already great answers about the advantages of using list initialization, however my personal rule of thumb is NOT to use curly braces whenever possible, but instead make it dependent on the conceptual meaning:

If the object I'm creating conceptually holds the values I'm passing in the constructor (e.g. containers, POD structs, atomics, smart pointers etc.), then I'm using the braces.

If the constructor resembles a normal function call (it performs some more or less complex operations that are parametrized by the arguments) then I'm using the normal function call syntax.

For default initialization I always use curly braces. For one, that way I'm always sure that the object gets initialized irrespective of whether it e.g. is a "real" class with a default constructor that would get called anyway or a builtin / POD type. Second it is - in most cases - consistent with the first rule, as a default initialized object often represents an "empty" object.

In my experience, this ruleset can be applied much more consistently than using curly braces by default, but having to explicitly remember all the exceptions when they can't be used or have a different meaning than the "normal" function-call syntax with parenthesis (calls a different overload).

It e.g. fits nicely with standard library-types like std::vector:

vector<int> a{10, 20};   //Curly braces -> fills the vector with the arguments

vector<int> b(10, 20);   //Parentheses -> uses arguments to parametrize some functionality,                          
vector<int> c(it1, it2); //like filling the vector with 10 integers or copying a range.

vector<int> d{};      //empty braces -> default constructs vector, which is equivalent
                      //to a vector that is filled with zero elements

Totally agree with most of your answer. However, don't you think putting empty braces for vector is just redundant? I mean, it is ok, when you need to value-initialize an object of generic type T, but what's the purpose of doing it for non-generic code?
@Mikhail: It is certainly redundant, but it is a habit of mine to always make local variable initialization explicit. As I wrote, this is mainly about consitency so I don't forget it, when it does matter. It is certainly nothing I'd mention in a code review or put in a style guide though.
pretty clean ruleset.
This is by far the best answer. {} is like inheritance - easy to abuse, leading to hard to understand code.
@MikeMB example: const int &b{} <- doesn't try to create an uninitialized reference, but binds it to a temporary integer object. Second example: struct A { const int &b; A():b{} {} }; <- doesn't try to create an uninitialized reference (as () would do), but bind it to a temporary integer object, and then leave it dangling. GCC even with -Wall doesn't warn for the second example.
X
Xeo

There are MANY reasons to use brace initialization, but you should be aware that the initializer_list<> constructor is preferred to the other constructors, the exception being the default-constructor. This leads to problems with constructors and templates where the type T constructor can be either an initializer list or a plain old ctor.

struct Foo {
    Foo() {}

    Foo(std::initializer_list<Foo>) {
        std::cout << "initializer list" << std::endl;
    }

    Foo(const Foo&) {
        std::cout << "copy ctor" << std::endl;
    }
};

int main() {
    Foo a;
    Foo b(a); // copy ctor
    Foo c{a}; // copy ctor (init. list element) + initializer list!!!
}

Assuming you don't encounter such classes there is little reason not to use the intializer list.


This is a very important point in generic programming. When you write templates, don't use braced-init-lists (the standard's name for { ... }) unless you want the initializer_list semantics (well, and maybe for default-constructing an object).
I honestly don't understand why the std::initializer_list rule even exists -- it just adds confusion and mess to the language. What's wrong with doing Foo{{a}} if you want the std::initializer_list constructor? That seems so much easier to understand than having std::initializer_list take precedence over all other overloads.
+1 for the above comment, because its a really mess I think!! it is not logic; Foo{{a}} follows some logic for me far more than Foo{a}which turns into intializer list precedence (ups might the user think hm...)
Basically C++11 replaces one mess with another mess. Oh, sorry it does not replace it - it adds to it. How can you know if you don't encounter such classes? What if you start without std::initializer_list<Foo> constructor, but it is going to be added to the Foo class at some point to extend its interface? Then users of Foo class are screwed up.
.. what are the "MANY reasons to use brace initialization"? This answer points out one reason (initializer_list<>), which it doesn't really qualify who says it's preferred, and then proceeds to mention one good case where it's NOT preferred. What am I missing that ~30 other people (as of 2016-04-21) found helpful?
A
Allan Jensen

It only safer as long as you don't build with -Wno-narrowing like say Google does in Chromium. If you do, then it is LESS safe. Without that flag the only unsafe cases will be fixed by C++20 though.

Note: A) Curly brackets are safer because they don't allow narrowing. B) Curly brackers are less safe because they can bypass private or deleted constructors, and call explicit marked constructors implicitly.

Those two combined means they are safer if what is inside is primitive constants, but less safe if they are objects (though fixed in C++20)


I tried noodling around on goldbolt.org to bypass "explicit" or "private" constructors using the sample code provided and making one or the other private or explicit, and was rewarded with the appropriate compiler error[s]. Care to back that up with some sample code?
This is the fix for the issue proposed for C++20: open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1008r1.pdf
If you edit your answer to show which version[s] of C++ you're talking about, I'd be happy to change my vote.
clang++ -std=c++14 tells me main.cpp:22:7: error: calling a private constructor of class 'Foo'. As far calling an explicit constructor implicitly, that argument doesn't even make sense. This is an implicit constructor call: foo_instance = false;. false is being implicitly converted to Foo by calling the matching constructor. If you use curly brackets, you are explicitly calling the constructor. The point being that you can't do such an assignment with curly braces without mentioning the type name.
c
codeling

Update (2022-02-11): Note that there are more recent opinions on that subject to the one originally posted (below), which argue against the preference of the {} initializer, such as Arthur Dwyer in his blog post on The Knightmare of Initialization in C++.

Original Answer:

Read Herb Sutter's (updated) GotW #1. This explains in detail the difference between these, and a few more options, along with several gotchas that are relevant for distinguishing the behavior of the different options.

The gist/copied from section 4:

When should you use ( ) vs. { } syntax to initialize objects? Why? Here’s the simple guideline: Guideline: Prefer to use initialization with { }, such as vector v = { 1, 2, 3, 4 }; or auto v = vector{ 1, 2, 3, 4 };, because it’s more consistent, more correct, and avoids having to know about old-style pitfalls at all. In single-argument cases where you prefer to see only the = sign, such as int i = 42; and auto x = anything; omitting the braces is fine. … That covers the vast majority of cases. There is only one main exception: … In rare cases, such as vector v(10,20); or auto v = vector(10,20);, use initialization with ( ) to explicitly call a constructor that is otherwise hidden by an initializer_list constructor. However, the reason this should be generally “rare” is because default and copy construction are already special and work fine with { }, and good class design now mostly avoids the resort-to-( ) case for user-defined constructors because of this final design guideline: Guideline: When you design a class, avoid providing a constructor that ambiguously overloads with an initializer_list constructor, so that users won’t need to use ( ) to reach such a hidden constructor.

Also see the Core Guidelines on that subject: ES.23: Prefer the {}-initializer syntax.