使用未初始化的成员复制结构

编程入门 行业动态 更新时间:2024-10-18 03:29:38
本文介绍了使用未初始化的成员复制结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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; }

更多推荐

使用未初始化的成员复制结构

本文发布于:2023-07-28 02:32:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1226484.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   成员   结构

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!