使用未初始化的成员复制结构 [英] Copying structs with uninitialized members

查看:89
本文介绍了使用未初始化的成员复制结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

复制一个未初始化其成员的结构是否有效?

Is it valid to copy a struct some of whose members are not initialized?

我怀疑这是未定义的行为,但如果这样,它将留下任何未初始化的成员在结构中(即使从未直接使用过这些成员)也很危险。所以我想知道标准中是否有允许它的东西。

I suspect it is undefined behavior, but if so, it makes leaving any uninitialized members in a struct (even if those members are never used directly) quite dangerous. So I wonder if there is something in the standard that allows it.

例如,这是否有效?

struct Data {
  int a, b;
};

int main() {
  Data data;
  data.a = 5;
  Data data2 = data;
}


推荐答案

是的,如果未初始化成员不是无符号的窄字符类型或 std :: byte ,那么使用隐式定义的复制构造函数复制包含此不确定值的结构在技术上是未定义的行为,因为它是用于复制具有相同类型不确定值的变量,原因是 [dcl.init] / 12

Yes, if the uninitialized member is not an unsigned narrow character type or std::byte, then copying a struct containing this indeterminate value with the implicitly defined copy constructor is technically undefined behavior, as it is for copying a variable with indeterminate value of the same type, because of [dcl.init]/12.

在这里适用,因为隐式生成的副本构造函数是,除了 union s,定义为直接复制每个成员,就像通过直接初始化一样,请参见 [class.copy.ctor] / 4

This applies here, because the implicitly generated copy constructor is, except for unions, defined to copy each member individually as if by direct-initialization, see [class.copy.ctor]/4.

这也是活动 CWG问题2264

我想在

如果您想100%确定,请使用 std :: memcpy 可轻松复制始终具有明确定义的行为 ,即使成员的价值不确定。

If you want to be 100% sure, using std::memcpy always has well-defined behavior if the type is trivially copyable, even if members have indeterminate value.

除了这些问题,您应该始终初始化类无论如何,只要您不要求该类具有 简单的默认构造函数 。您可以使用默认的成员初始化器语法例如值初始化成员:

These issues aside, you should always initialize your class members properly with a specified value at construction anyway, assuming you don't require the class to have a trivial default constructor. You can do so easily using the default member initializer syntax to e.g. value-initialize the members:

struct Data {
  int a{}, b{};
};

int main() {
  Data data;
  data.a = 5;
  Data data2 = data;
}

这篇关于使用未初始化的成员复制结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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