By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,192 Members | 867 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,192 IT Pros & Developers. It's quick & easy.

More new MyClass; vs. new MyClass();

P: n/a

Hello all,

Below is an adaptation of an example Victor gave for testing compiler
behavior with regard to the issue of the difference between new MyClass; and
new MyClass();.

I have included in comment form the behavior on my platform.

Is this behavior that of C++98, C++2003 or neither?

Thanks,
Dave
#include <iostream>
#include <string>

using namespace std;

struct A
{
int a;
string str;
};

struct B
{
int a;
};

int main()
{
// Experiment 1
cout << "Experiment 1:" << endl;

char *storage_1 = new char[sizeof(A)];

for (int i = 0; i < sizeof(A); ++i)
storage_1[i] = 1;

// 16843009
cout << reinterpret_cast<A *>(storage_1)->a << endl;

A *pa_1 = new(storage_1) A;
cout << pa_1->a << endl; // 16843009

pa_1 = new(storage_1) A();
cout << pa_1->a << endl; // 16843009

delete[] storage_1;

// Experiment 2
cout << endl;
cout << "Experiment 1:" << endl;

char *storage_2 = new char[sizeof(B)];

for (int i = 0; i < sizeof(B); ++i)
storage_2[i] = 1;

// 16843009
cout << reinterpret_cast<B *>(storage_2)->a << endl;

B *pa_2 = new(storage_2) B;
cout << pa_2->a << endl; // 16843009

pa_2 = new(storage_2) B();
cout << pa_2->a << endl; // 0

delete[] storage_2;
}
Jul 22 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a

"Dave" <be***********@yahoo.com> wrote in message news:vt************@news.supernews.com...

A *pa_1 = new(storage_1) A;
cout << pa_1->a << endl; // 16843009
This is undefined behavior (as Victor warned you). The
value of a is indeterminate.

A is default initialized...A is non-POD class type so the
implicitly generated default constructor is run and that leaves
the a member uninitialized.

pa_1 = new(storage_1) A();
cout << pa_1->a << endl; // 16843009
This is a compiler bug under 2003. The value-initialization requires
the elements without constructors to be zero initialized.

Under the 1998, the value was indeterminate. The behavior was the
same as the first case (default initialization).

B *pa_2 = new(storage_2) B;
cout << pa_2->a << endl; // 16843009
Again undefined behavior. POD's are never initialized like this.

pa_2 = new(storage_2) B();
cout << pa_2->a << endl; // 0


This is the correct behavior in either case. In 98, the pod would be default
(zero) initialized. In 98, the pod would be value initialized which ends up
zero initializing al.
Jul 22 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.