初始化 C 结构的正确方法

新手上路,请多包涵

我们的代码涉及一个 POD(普通旧数据结构)结构(它是一个基本的 c++ 结构,其中包含其他结构和 POD 变量,需要在开始时进行初始化。)

根据我 读过 的内容,似乎:

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

应该将所有值初始化为零,如下所示:

 myStruct = new MyStruct();

但是,当以第二种方式初始化结构时,Valgrind 后来在使用这些变量时抱怨“条件跳转或移动取决于未初始化的值”。我的理解在这里有缺陷,还是 Valgrind 抛出误报?

原文由 KC3BZU 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 412
2 个回答

在 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”将提供比我更好的解释。

原文由 Martin York 发布,翻译遵循 CC BY-SA 4.0 许可协议

    You can declare and initalise structure in C++ this way also:::

    struct person{
        int a,h;

        person(int a1,int h1): a(a1),h(h1){

        }// overriden methods

        person():a(0),h(0){

        }// by default
    };

   struct person p;
   --> This creates from by default Person Age: 0 height: 0

   struct person p = person(3,33);
    --> This creates from overriden methods Person Age: 3 height: 33




原文由 Bhanu Mahto 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题