Chinaunix首页 | 论坛 | 博客
  • 博客访问: 871232
  • 博文数量: 158
  • 博客积分: 4380
  • 博客等级: 上校
  • 技术积分: 2367
  • 用 户 组: 普通用户
  • 注册时间: 2006-09-21 10:45
文章分类

全部博文(158)

文章存档

2012年(158)

我的朋友

分类: C/C++

2012-11-23 16:02:09

此文有问题

struct foo
{
    int val;
};

#include

int main( void )
{
    using namespace std;

    foo* p1 = new foo();
    foo* p2 = new foo;

    foo* p3 = new foo[2]();
    foo* p4 = new foo[2];

    cout << p1->val << endl; // val被初始化为int(),即0
    cout << p2->val << endl; // val为随机值

//    cout << p3->val << endl; // val被初始化为int(),即0
//    cout << p4->val << endl; // val为随机值
   
    return 0;
}


2008-01-10:
ISO/IEC 14882:2003(E) 中 5.3.4 之 15
— If the new-initializer is omitted:
    — If T is a (possibly cv-qualified) non-POD class type (or array thereof), the object is default-initialized(8.5). If T is a const-qualified type, the underlying class type shall have a user-declared default constructor.
    — Otherwise, the object created has indeterminate value. If T is a const-qualified type, or a (possibly cv-qualified) POD class type (or array thereof) containing (directly or indirectly) a member of const-qualified type, the program is ill-formed;
— If the new-initializer is of the form (), the item is value-initialized (8.5);

阅读(1851) | 评论(14) | 转发(0) |
给主人留下些什么吧!~~

网友评论2012-11-23 16:04:26

葵花
觉得 空见 的看法有道理哦,不知星星怎么说?

网友评论2012-11-23 16:04:18

isold
任何变量都要有个初始值,这样还是比较好的习惯。

网友评论2012-11-23 16:04:11

空见
编译器在有必要的时候才合成构造函数,这里结构只有一个整型的成员,整型没有缺省构造,所以编译器不会去合成缺省构造,所以当new foo 和 new foo()的时候都没有调用缺省构造函数,没有合成嘛,没的调用。
而当new foo()的时候,编译器添加了一段memset的代码将内存置0,这个行为我的记忆中不是标准规定的,好像《inside c++ object module》中有提到这个问题,即有的编译器会置0,有的不会。
如果面试考到这样的题,那是出题的人有毛病,这样的编程风格极不提倡,简直就是茴香豆的茴字有四种写法的翻版,如果依赖成员的初始值,就应该自己定义构造函数,不能依赖编译器

网友评论2012-11-23 16:04:01

shen.hen.en.n
星星很强!
这道题 很多面试得公司都会带到.

网友评论2012-11-23 16:03:54

呵呵
能否把反汇编的结果show一下