正确的方式来初始化C ++结构 [英] Proper way to initialize C++ structs

查看:154
本文介绍了正确的方式来初始化C ++结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



根据我阅读,似乎:

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

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

  myStruct = new MyStruct();然而,当结构以第二种方式初始化时,Valgrind后来抱怨条件跳转或移动取决于当未初始化值时使用这些变量。我在这里的理解是有缺陷的,还是Valgrind抛出的假阳性?

解决方案

在C ++类/ structs是相同的)。



非POD结构也可以有一个构造函数,所以它可以初始化成员。

如果你的结构体是一个POD,那么你可以使用一个初始化程序。

  struct C 
{
int x;
int y;
};

C c = {0}; // Zero initialize POD

也可以使用默认构造函数。

  C c = C(); //使用默认构造函数的零初始化
C * c = new C(); //零初始化动态分配的对象。

//注意上面和初始化版本的构造函数之间的区别。
//注:所有上述注释适用于POD结构。
C c; //成员是随机的
C * c = new C; //成员是随机的(更官方未定义)。



我相信valgrind抱怨,因为这是C ++如何工作。 (我不知道什么时候C ++升级与零初始化默认构造)。最好的办法是添加一个初始化对象的构造函数(结构体是允许的构造函数)。



注意:

很多初学者尝试重命名init:

  C c(); //不幸的是这不是一个变量声明。 

//正确的方法是:
C c = C();

快速搜索Most Vexing Parse将提供比我更好的解释。 p>

Our code involves a POD (Plain Old Datastructure) struct (it is a basic c++ struct that has other structs and POD variables in it that needs to get initialized in the beginning.)

Based one what I've read, it seems that:

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

should initialize all the values to zero, as does:

myStruct = new MyStruct();

However, when the struct is initialized in the second way, Valgrind later complains "conditional jump or move depends on uninitialised value(s)" when those variables are used. Is my understanding flawed here, or is Valgrind throwing false positives?

解决方案

In C++ classes/structs are identical (in terms of initialization).

A non POD struct may as well have a constructor so it can initialize members.
If your struct is a POD then you can use an initializer.

struct C
{
    int x; 
    int y;
};

C  c = {0}; // Zero initialize POD

Alternatively you can use the default constructor.

C  c = C();      // Zero initialize using default constructor
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).

I believe valgrind is complaining because that is how C++ used to work. (I am not exactly sure when C++ was upgraded with the zero initialization default construction). Your best bet is to add a constructor that initializes the object (structs are allowed constructors).

As a side note:
A lot of beginners try to value init:

C c(); // Unfortunately this is not a variable declaration.

// The correct way to do this is:
C c = C();

A quick search for the "Most Vexing Parse" will provide a better explanation than I can.

这篇关于正确的方式来初始化C ++结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆