5

c++ constructor | 重归混沌的BLOG

 3 years ago
source link: https://blog.gotocoding.com/archives/562
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C++默认构造函数

在C++中,如果不为某个struct/class实现一个构造函数,那么编译器就会自动为这个类添加一个默认构造函数,而这个默认构造函数什么也不干。

但是我却从来不知道,默认构造函数在不同的情况下,会出现不一样的效果(当然这是C++03之后的标准).

先看一段代码:

struct test {
int a;
int b;
};


void *operator new(size_t sz)
{
void *p = malloc(sz);
for (size_t i = 0; i < sz; i++)
((char *)p)[i] = 0x01;
return p;
}
int main()
{
struct test *t1 = new test;
struct test *t2 = new test();
printf("t1:%x-%x\n", t1->a, t1->b);
printf("t2:%x-%x\n", t2->a, t2->b);
return 0;
}

重载new操作符是为了把分配出来的内存弄脏。然后观察new test和new test()的区别。

结果出人意料,t1的值就是内存中被污染的值,然后t2的值却全部被清0,而造成这种现象的惟一的区别就是new之后类型是否带有括号。

这就是C++03版本的新增内容,当没有实现构造函数时,编译器为你自动生成的构造函数是有两种用途的。当你在使用new T()构造对象时,默认的构造函数会对各变量执行清0操作,其实应该就是memset为0. 而在使用new T来构造对象时,其默认构造函数是任何事也不做的。

总觉得这么做违背了语言的一致性的设计, 但是不管怎么说有了这个,在写struct定义时在一定的情况下就可以省掉默认构造函数了。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK