#include <iostream> class T { int x; public: T() { std::cout << "constr\n"; } ~T() { std::cout << "destr\n"; } }; int main (void) { char *buf = new char[sizeof(T)]; //13 line T *t = new(buf) T; t->~T(); }
What kind of memory allocation is new(buf)
? That is, memory is allocated in line 13, and then in line 14 no new memory is allocated for an object of type T
, but the already allocated memory from that pointed to by buf
is taken. That is, this method takes less action, because you can allocate a lot of memory once and then use it with the help of new(buf)
when dynamically allocating objects. If this is the case, then the pointer will point to the next free memory cell of the selected area, when, for example, there is another allocation T *t2 = new(buf) T;
that is, buf points to a chunk of space about the size of a class T and therefore overwrites the memory pointed to by *t
. And yet it is not clear how this is implemented. Since new
is an operator, there probably is its overloaded version, which takes a pointer to the memory already allocated and the second parameter is the object that needs to be allocated in it. In general, this is all speculation and maybe I'm completely wrong about this. So it would be best if you wrote what they called it, so that you could at least read about this method somewhere or explain it as you see fit.
T
in memory at the address contained in the pointerbuf
. So dynamic memory forT
in thisnew
will not be allocated and the destructor must be called manually, before delete [] buf. - avpnew()
address. This was already mentioned in the comments. And new returns the address buf (you can check). At the same time look at addresses with char buf [sizeof (T)]; - avpT t()
, the default constructors for all fields will be called. In the case of int, the zero will simply be written, in the case of std :: string, its constructor will be called (it is much more complicated inside). If there is a callT t
, then there are two options. If the object has a default constructor (T()
), then it will be called. If it is not, then no one will be reset. Here are three helpful links 1 , 2 and 3 . - KoVadim