用大括号给非数组对象赋值合法吗?

Is it legitimate to assign values to non-array objects with braces?

我偶然发现这在程序主体中有效:(当前使用 g++ 5.2.0)

Vector4  pos;  
pos = {0.0, 1.1, 2.2, 3.3};  

Vector4 class 将此数据声明为命名变量:

double  t, x, y, z;  

不是数组,也没有自动转换 cnstrs。

我猜内存存储是连续的,所以编译器可以弄清楚要做什么。但这是合法的使用,还是可以使用未分配的内存,或者可能有其他问题?

引用自cppreference.com

If the right operand is a braced-init-list

  • the expression E1 = {} is equivalent to E1 = T{}, where T is the type of E1.

  • the expression E1 = {E2} is equivalent to E1 = T{E2}, where T is the type of E1.

For class types, the syntax E = {e1, e2, e3} generates a call to the assignment operator with the braced-init-list as the argument, which then selects the appropriate assignment operator following the rules of overload resolution

因此您的代码等同于

pos = Vector4{0.0, 1.1, 2.2, 3.3};

编译器执行aggregate initialization一个临时对象,然后使用Vector4的赋值运算符,将结果对象赋值给pos

使用绝对安全。请注意,如果您的 Vector4 是非聚合(例如,具有用户定义的构造函数),则聚合初始化将不起作用(即,您会遇到编译时错误)。所以代码编译的事实意味着你是安全的。

伙计们,谢谢你的解释。一个简单的测试程序显示默认的 cnstr 被调用两次,然后是赋值运算符。它们是:

Vector4() : t(0.0), x(0.0), y(0.0), z(0.0) {}

Vector4 const &operator =(const Vector4 &v) {
    if(this != &v) {t=v.t; x=v.x; y=v.y; z=v.z;}
    return *this;  
}