9

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>();
4

1 回答 1

0

C++的初始化规则相当复杂。它们在标准第 8 章(第 8 章)的后半部分进行了描述。有零初始化、直接初始化、值初始化、复制初始化、列表初始化等等,每个都可以根据上下文(声明、参数、返回、抛出、成员初始化器等)进行不同的交互),要绑定的类型的属性和输入初始化表达式或花括号初始化列表。语言设计者还以几乎向后兼容 C 和旧版本的 C++ 为目标,这限制了他们可以做的事情。推测初始化规则更改的后果需要进行大量研究,并且更改可能会产生许多意外的极端情况。如果你'

于 2013-06-11T20:32:18.310 回答