Sha*_*503 70 c++ struct valgrind initialization calloc
我们的代码涉及一个POD(Plain Old Datastructure)结构(它是一个基本的c ++结构,其中包含其他结构和POD变量,需要在开始时进行初始化.)
根据我所读到的,似乎:
myStruct = (MyStruct*)calloc(1, sizeof(MyStruct));
Run Code Online (Sandbox Code Playgroud)
应该将所有值初始化为零,如下所示:
myStruct = new MyStruct();
Run Code Online (Sandbox Code Playgroud)
但是,当以第二种方式初始化结构时,Valgrind后来抱怨"当使用这些变量时,条件跳转或移动取决于未初始化的值".我的理解是否存在缺陷,或者Valgrind是否会误报?
Mar*_*ork 102
在C++中,类/结构是相同的(就初始化而言).
非POD结构也可以有一个构造函数,因此它可以初始化成员.
如果您的结构是POD,那么您可以使用初始化程序.
struct C
{
int x;
int y;
};
C c = {0}; // Zero initialize POD
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用默认构造函数.
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).
Run Code Online (Sandbox Code Playgroud)
我相信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();
Run Code Online (Sandbox Code Playgroud)
快速搜索"最令人烦恼的解析"将提供比我更好的解释.
| 归档时间: |
|
| 查看次数: |
165358 次 |
| 最近记录: |