我们的代码涉及一个 POD(普通旧数据结构)结构(它是一个基本的 c++ 结构,其中包含其他结构和 POD 变量,需要在开始时进行初始化。)
基于我所拥有的 read ,看来:
myStruct = (MyStruct*)calloc(1, sizeof(MyStruct));
应该将所有值初始化为零,如下所示:
myStruct = new MyStruct();
但是,当以第二种方式初始化结构时,Valgrind 稍后会在使用这些变量时提示“条件跳转或移动取决于未初始化的值”。是我的理解有缺陷,还是 Valgrind 抛出了误报?
最佳答案
在 C++ 中,类/结构是相同的(就初始化而言)。
一个非 POD 结构也可以有一个构造函数,以便它可以初始化成员。
如果您的结构是 POD,那么您可以使用初始化程序。
struct C
{
int x;
int y;
};
C c = {0}; // Zero initialize POD
您也可以使用默认构造函数。
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++)。最好的办法是添加一个初始化对象的构造函数(结构体是允许的构造函数)。
附注:
很多初学者都尝试重视 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”将提供比我更好的解释。
关于c++ - 初始化 C++ 结构的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5914422/