c++ - 初始化 C++ 结构的正确方法

标签 c++ struct initialization valgrind calloc

我们的代码涉及一个 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/

相关文章:

c - 类型转换 2 个具有不同数量变量的结构

arrays - 如何在线程中访问perl对象

c++ - 带有堆的 Bellman-Ford 不适用于自定义比较功能

c++ - clang-format:禁用宏的格式?

c++ - 是否可以存储迭代器?

c# - List<struct> 与 List<class> 的性能

arrays - 使用结构体存储动态数据

initialization - 如何决定使用哪种模式进行 'kaiming_normal' 初始化

iphone - 如何重用UILabel? (或任何物体)

c++ - 从 WinAPI 线程调用 omp_set_num_threads 时出现问题