list-initialization

Why can I not brace initialize a struct derived from another struct?

五迷三道 提交于 2019-11-26 06:45:24
问题 When I run this code: struct X { int a; }; struct Y : public X {}; X x = {0}; Y Y = {0}; I get: error: could not convert ‘{0}’ from ‘<brace-enclosed initializer list>’ to ‘Y’ Why does brace initialization work for the base class but not the derived class? 回答1: Your problem has to do with aggregate initialization: struct X is an aggregate while struct Y is not. Here is the standard quote about aggregates (8.5.1): An aggregate is an array or a class (Clause 9) with no user-provided constructors

Deleted default constructor. Objects can still be created… sometimes

╄→гoц情女王★ 提交于 2019-11-26 06:29:54
问题 The naive, optimistic and oh.. so wrong view of the c++11 uniform initialization syntax I thought that since C++11 user-defined type objects should be constructed with the new {...} syntax instead of the old (...) syntax (except for constructor overloaded for std::initializer_list and similar parameters (e.g. std::vector : size ctor vs 1 elem init_list ctor)). The benefits are: no narrow implicit conversions, no problem with the most vexing parse, consistency(?). I saw no problem as I thought

Why is list initialization (using curly braces) better than the alternatives?

主宰稳场 提交于 2019-11-25 22:39:37
问题 MyClass a1 {a}; // clearer and less error-prone than the other three MyClass a2 = {a}; MyClass a3 = a; MyClass a4(a); Why? I couldn\'t find an answer on SO, so let me answer my own question. 回答1: 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