More new MyClass; vs. new MyClass();

D

Dave

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 = 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 = 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;
}
 
R

Ron Natalie

Dave said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,586
Members
45,086
Latest member
ChelseaAmi

Latest Threads

Top