C ++初始化器列表的元素少于struct [英] C++ initializer lists with fewer elements than the struct

查看:126
本文介绍了C ++初始化器列表的元素少于struct的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用初始化列表创建一个结构,但初始化列表包含比我的结构更少的元素,我看到剩余的元素用零初始化。

When I use an initializer list to create a struct, but the initializer list contains fewer elements than my struct, I see the remaining elements are initialized with zeroes.

这是一个未定义的行为,我看到零,因为我的编译器(VS2015)决定为我的内存零。

Is this an undefined behaviour and I'm seeing zeroes because my compiler (VS2015) decided to zero the memory for me?

或者有人可能指向我的文档解释这个行为在C ++中?

Or could someone point me to the documentation that explains this behaviour in C++?

这是我的代码:

struct Thing {
    int value;
    int* ptr;
};


void main() {
    Thing thing { 5 };
    std::cout << thing.value << " " << thing.ptr << std::endl;
}

这是它打印的:

5 00000000

推荐答案

这是一个定义的行为。根据聚合初始化的规则,剩余成员 ptr 值初始化,即零初始化为NULL指针。

This is defined behaviour. According to the rule of aggregate initialization, the remaining member ptr will be value-initialized, i.e. zero-initialized to NULL pointer.

(强调我的)


如果initializer子句的数目小于 (因为C ++ 17)或初始化器列表是完全空的,剩余的成员和基数(自C ++ 17以来) c $ c>通过它们的默认初始化器,如果在类定义中提供,否则(由于C ++ 14)由空列表,根据通常的列表初始化规则>具有默认构造函数的非类类型和非聚合类的值初始化,以及聚合的聚合初始化)。如果引用类型的成员是这些剩余成员之一,则该程序是错误的。

If the number of initializer clauses is less than the number of members and bases (since C++17) or initializer list is completely empty, the remaining members and bases (since C++17) are initialized by their default initializers, if provided in the class definition, and otherwise (since C++14) by empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates). If a member of a reference type is one of these remaining members, the program is ill-formed.

这篇关于C ++初始化器列表的元素少于struct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆