简体   繁体   中英

Why uniform initialization syntax is applied only for objects?

In c++11 we have nice uniform initialization syntax for objects. Why it does not extends to initialize non-object types as well?

Is there any syntactic ambiguity for that, or is it just some stupid question I am asking?

Example:

struct s{ int k;};
s s1{1}; //ok (object initialization)
s const& s3{3};  //ok (object initialization)
s& s2{s1};  //error (reference initialization)

A more useful example:

struct t{ t(t const& x) : k(x.k){} int k;};
struct c
{
  c(t& x1,t& x2) 
    : s1_{x1} //error (reference initialization)
    , s2_{x2} //ok (object initialization)
   {}
 t& s1_;
 t s2_;
};

Another one :

template<class T>
T get()
{
   return T{};
}

//ok (object initialization)
get<int>(); 
//error (void initialization? I do not know terminology for void() token equivalent)
get<void>();

The initialization rules of C++ are quite complicated. They are described in the second half of chapter (clause) 8 of the standard. There is zero-initialization, direct-initialization, value-initialization, copy-initialization, list-initialization to name just a few, and each can have different interactions depending on the context (declaration, parameter, return, throw, member initializer, etc), properties of the type to be bound and input initialization expression or braced-init-list. The language designers also make it a goal to be almost backwards compatible with C and older versions of C++, which restricts what they can do. It takes quite some study to speculate on the ramifications of changes to the initialization rules, and changes can generate a lot of unintended corner cases. If you're interested I encourage you to study the standard and try to work through the implications of a proposed change you have designed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM