初始化 C++ 结构的正确方法 [英] Proper way to initialize C++ structs

查看:27
本文介绍了初始化 C++ 结构的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的代码涉及一个 POD(Plain Old Datastructure)结构(它是一个基本的 c++ 结构,其中包含其他结构和 POD 变量,需要在开始时进行初始化.)

Our code involves a POD (Plain Old Datastructure) struct (it is a basic c++ struct that has other structs and POD variables in it that needs to get initialized in the beginning.)

基于我阅读的内容,似乎:

myStruct = (MyStruct*)calloc(1, sizeof(MyStruct));

应该将所有值初始化为零,就像这样:

should initialize all the values to zero, as does:

myStruct = new MyStruct();

然而,当以第二种方式初始化结构体时,Valgrind 稍后会在使用这些变量时抱怨条件跳转或移动取决于未初始化的值".是我的理解有问题,还是 Valgrind 抛出了误报?

However, when the struct is initialized in the second way, Valgrind later complains "conditional jump or move depends on uninitialised value(s)" when those variables are used. Is my understanding flawed here, or is Valgrind throwing false positives?

推荐答案

在 C++ 中,类/结构是相同的(在初始化方面).

In C++ classes/structs are identical (in terms of initialization).

一个非 POD 结构也可以有一个构造函数,以便它可以初始化成员.
如果您的结构是 POD,那么您可以使用初始化程序.

A non POD struct may as well have a constructor so it can initialize members.
If your struct is a POD then you can use an initializer.

struct C
{
    int x; 
    int y;
};

C  c = {0}; // Zero initialize POD

或者,您可以使用默认构造函数.

Alternatively you can use the default constructor.

C  c = C();      // Zero initialize using default constructor
C  c{};          // Latest versions accept this syntax.
C* c = new C();  // Zero initialize a dynamically allocated object.

// Note the difference between the above and the initialize version of the constructor.
// Note: All above comments apply to POD structures.
C  c;            // members are random
C* c = new C;    // members are random (more officially undefined).

我相信 valgrind 正在抱怨,因为这就是 C++ 过去的工作方式.(我不确定何时使用零初始化默认构造升级 C++).最好的办法是添加一个初始化对象的构造函数(结构体是允许的构造函数).

I believe valgrind is complaining because that is how C++ used to work. (I am not exactly sure when C++ was upgraded with the zero initialization default construction). Your best bet is to add a constructor that initializes the object (structs are allowed constructors).

附注:
很多初学者都试图重视 init:

As a side note:
A lot of beginners try to value init:

C c(); // Unfortunately this is not a variable declaration.
C c{}; // This syntax was added to overcome this confusion.

// The correct way to do this is:
C c = C();

快速搜索Most Vexing Parse"会提供比我更好的解释.

A quick search for the "Most Vexing Parse" will provide a better explanation than I can.

这篇关于初始化 C++ 结构的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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