简体   繁体   English

C ++中的默认结构初始化

[英]Default Struct Initialization in C++

Say I have a struct that looks like this (a POD): 假设我有一个看起来像这样的结构(一个POD):

struct Foo
{
  int i;
  double d;
};

What are the differences between the following two lines: 以下两行之间有什么区别:

Foo* f1 = new Foo;
Foo* f2 = new Foo();

The first one leaves the values uninitialised; 第一个是未初始化的值; the second initialises them to zero. 第二个将它们初始化为零。 This is only the case for POD types, which have no constructors. 这只是POD类型的情况,它没有构造函数。

I suppose nothing at all. 我什么都没想。 Foo() is allowed, even if it makes no sense... I've tried to change struct into class and tried a diff on the generated exe, and they resulted to be the same, meaning that a class without method is like a struct from a practical and "effective" point of view. 允许Foo() ,即使它没有任何意义......我已经尝试将struct更改为class并在生成的exe上尝试了diff,它们也是相同的,这意味着没有方法的类就像一个结构从实际和“有效”的角度来看。

But : if you use only one of the alternative, keeping struct or class no matter, it happens that new Foo and new Foo() gives executables which differ! 但是 :如果你只使用其中一个替代方法,保留structclass ,那么new Foonew Foo()会给出不同的可执行文件! (At least using g++) Ie (至少使用g ++)即

struct Foo { int i; double d; }
int main() { Foo *f1 = new Foo; delete f1; }

is compiled into somehing different from 编译成不同的somehing

struct Foo { int i; double d; }
int main() { Foo *f1 = new Foo(); delete f1; }

and the same happens with class instead of struct . 同样的事情发生在class而不是struct To know where the difference is we should look at the generated code... and to know if it is a g++ idiosincracy or not, I should try another compiler but I have only gcc and no time now to analyse the asm output of g++... 要知道差异在哪里,我们应该看看生成的代码......并且要知道它是否是g ++ idiosincracy,我应该尝试另一个编译器,但我只有gcc,现在没时间分析g ++的asm输出。 ..

Anyway from a "functional" (practical) point of view, it is the same thing. 无论从“功能”(实际)的角度来看,它都是一回事。

Add

At the end it is always better to know or do deeper investigation for some common human problems on Q/A sites... the only difference in the code generated by g++ in () and no () cases, 最后,对Q / A站点上的一些常见人类问题进行了解或进行更深入的调查总是更好... ... g ++在()和no()情况下生成的代码的唯一区别,

movl    $0, (%eax)
    fldz
    fstpl   4(%eax)

which is a fragment that initializes to 0/0.0 the int and the double of the struct... so Seymour knows it better (but I could have discovered it without knowing if I had taken a look at the asm first!) 这是一个片段,初始化为0 / 0.0的int和结构的两倍...所以Seymour更了解它(但我可以在不知道我是否先看过asm的情况下发现它!)

Per the link I posted. 根据我发布的链接。

In C++ the only difference between a class and a struct is that class-members are private by default, while struct-members default to public. 在C ++中,类和结构之间的唯一区别是类成员默认是私有的,而struct-members默认为public。 So structures can have constructors, and the syntax is the same as for classes. 所以结构可以有构造函数,语法和类相同。

Struct Constructor Info 结构构造器信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM