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

| 我们的代码涉及一个POD(普通旧数据结构)结构(它是一种基本的c ++结构,其中具有其他结构和POD变量,需要在开始时对其进行初始化。) 根据我已阅读的内容,似乎:
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();
快速搜索“最令人烦恼的解析”将提供比我更好的解释。     
根据您告诉我们的信息,它在valgrind中确实是错误的肯定。假设对象是POD,则带有
()
new
语法应将对象值初始化。 您的结构的某些子部分是否可能实际上不是POD,并且阻止了预期的初始化?您是否可以将代码简化为仍可标记valgrind错误的可发布示例? 或者,也许您的编译器实际上并未对POD结构进行值初始化。 在任何情况下,最简单的解决方案可能是根据struct / subparts的需要编写构造函数。     
我写一些测试代码:
#include <string>
#include <iostream>
#include <stdio.h>

using namespace std;

struct sc {
    int x;
    string y;
    int* z;
};

int main(int argc, char** argv)
{
   int* r = new int[128];
   for(int i = 0; i < 128; i++ ) {
        r[i] = i+32;
   }
   cout << r[100] << endl;
   delete r;

   sc* a = new sc;
   sc* aa = new sc[2];
   sc* b = new sc();
   sc* ba = new sc[2]();

   cout << \"az:\" << a->z << endl;
   cout << \"bz:\" << b->z << endl;
   cout << \"a:\" << a->x << \" y\" << a->y << \"end\" << endl;
   cout << \"b:\" << b->x << \" y\" << b->y <<  \"end\" <<endl;
   cout << \"aa:\" << aa->x << \" y\" << aa->y <<  \"end\" <<endl;
   cout << \"ba:\" << ba->x << \" y\" << ba->y <<  \"end\" <<endl;
}
g ++编译并运行:
./a.out 
132
az:0x2b0000002a
bz:0
a:854191480 yend
b:0 yend
aa:854190968 yend
ba:0 yend
    
您需要初始化您在结构中拥有的任何成员,例如:
struct MyStruct {
  private:
    int someInt_;
    float someFloat_;

  public:
    MyStruct(): someInt_(0), someFloat_(1.0) {} // Initializer list will set appropriate values

};
    
由于它是POD结构,因此您始终可以将其设置为0-这可能是初始化字段的最简单方法(假设合适)。     

要回复问题请先登录注册