构造时有无()的区别

构造时有无()的区别

当有()时,会将申请到的成员变量的空间初始化,没有时则不会

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <stdio.h>
using namespace std;
class foo {
public:
//foo() { cout << "foo's constructor" << endl; }
//~foo() { cout << "foo's destructor" << endl; }
int a;
};
int main() {
char buf[sizeof(foo)];
foo* a = new (buf) foo;//不会将申请到的int空间初始化
char buf2[sizeof(foo)];
foo* b = new (buf2) foo();//则会将申请到的int空间初始化为0。
printf("%d %d\n", a->a, b->a);
return 0;
}