中的汇总初始化安全性

中的汇总初始化安全性

本文介绍了C ++中的汇总初始化安全性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有以下结构:

struct sampleData
{
       int x;
       int y;
};

使用时,我想初始化 sampleData 类型为已知状态。

And when used, I want to initialize variables of sampleData type to a known state.

sampleData sample = { 1, 2 }

后来,我决定需要存储在 sampleData 结构中的其他数据,如下所示:

Later, I decide that I need additional data stored in my sampleData struct, as follows:

struct sampleData
{
       int x;
       int y;
       int z;
};

据我了解,前个剩下的两个字段初始化z 数据结构仍然是有效的语句,将被编译。使用默认值填充缺少的字段。

It is my understanding that the two field initialization left over from my pre-z data structure is still a valid statement, and will be compiled., populating the missing fields with default values.

这种理解正确吗?我最近在Ada上工作,它也允许聚合初始化,但是会将类似的问题标记为编译错误。假设我对上述C ++代码的假设是正确的,是否有一种语言构造可以将缺少的初始化值识别为错误?

Is this understanding correct? I have been working recently in Ada, which also allows aggregate initialization, but which would flag a similar issue as a compilation error. Assuming that my assumptions about the C++ code above are correct, is there a language construct which would recognize missing initialization values as an error?

推荐答案

仅通过。

如果添加构造函数,那么问题就解决了,但是您将需要稍稍更改语法,并且失去将 struct 存储在 union 中的能力。

If you add constructor(s) then then problem goes away, but you'll need to change the syntax a little and you lose the ability to store the struct in a union (among other things).

struct sampleData
{
    sampleData(int x, int y) : x(x), y(y) {}
    int x;
    int y;
};

sampleData sample( 1, 2 );

添加 z (并更改构造函数)会将 sample(1,2)标记为编译错误。

Adding z (and changing the constructor) will mark sample( 1, 2 ) as a compile error.

这篇关于C ++中的汇总初始化安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 18:58