Separate new and constructor

Look at this code:

string* ps=new string("hello, world");

As is known this code first allocate a memory block of sizeof(string), then call string’s constructor to "make the memory be a string object".

Seems C++ use this design to avoid memory being miss used, however there’re situations in which you want to separate the two, for example:

1. You just want to allocate some memory that can hold a string object, you don’t want to call its constructor immediately after the allocation.

2. You all ready have a block of memory, you want the constructor can be called on the memory you provide.

Well, simply look at this 100% OK C++ code:

{
    string* ps=(string*)(::operator new(sizeof(string))); // this allocates memory for a string
    ::new(ps) string("hello, world"); // call constructor of string on ps
    t->~TS(); // call its destructor without free the memory
    ::operator delete(t); // free the memory
}

posted on 2009-09-12 20:51  Tactoth  阅读(138)  评论(0编辑  收藏  举报

导航