About operator new() ......

class MyAx{
....
};

int main()
{
void *p = reinterpret_cast<void *>(0xf1234);
MyAx *mxx = new(p) MyAx;//the default construct is processed
cout << mxx->xxx << endl;
MyAx *mxc = (MyAx *)MyAx::operator new(sizeof(MyAx),p);//the default construct is not processed
cout << mxx->xxx << endl;
system("pause");
return 0;
}

why? Does the compiler do something back?
There are 3 news:

1) "operator new" allocates memory, but does not construct an object

1
2
3
MyAx* p = (MyAx*) operator new(sizeof(MyAx));
// memory is allocated, but 'p' does not yet point to an actual MyAx object
//  because nothing was constructed 


2) "placement new" constructs an object at a given address, but does not allocate any memory:

1
2
int memorybuffer[100];
MyAx* p = new(memorybuffer) MyAx;  // constructs a MyAx object in the 'memorybuffer' memory 


3) plain old "new" does both. Allocates memory and creates an object

 
MyAx* p = new MyAx;  // allocates memory and constructs an object there. 
Topic archived. No new replies allowed.