gosom gosom - 1 month ago 14
C++ Question

Understanding c++ new operator

Assume that ITEM is a class

ITEM* items = new ITEM[10];
for(i=0;i<10;++i)
new(&items[i)ITEM();
new(&items[0])ITEM(items[1]);


Is the above valid?

The way I understand it is that the last 2 uses of the new operator
do not allocate memory. They just invoke the constructor of ITEM.

Is the above equivalent to?

ITEM* items = new ITEM[10];
for(i=0;i<10;++i)
items[i] = ITEM();
item[0] = ITEM(items[1]);


EDIT:

https://github.com/gosom/practice-cpp/blob/master/arrays/darray.h

I use it here (for practicing)

Answer

The way I understand it is that the last 2 uses of the new operator do not allocate memory. They just invoke the constructor of ITEM.

Yes. This is the "placement new" operator, wich does not allocate memory and calls object constructor. This is legal to proceed the way you do, though ITEM constructor will be called twice (meaning that the ITEM class constructor will be executed twice: one when standard new is called, one when placement new is called). This may lead to memory leak (or other unexpected behavior) if some ressources are allocated in ITEM's constructor. See this for more info about placement new.

Is the above equivalent to?

No, this is not equivalent. In the latter case, you create a temporary object at each loop, which you copy to item[i]. This will call ITEM constructor, assignment operator, and destructor, at each loop. In the previous situation, placement new only calls ITEM constructor, nothing else.

The typical usage of "placement new" is when you want your object to be allocated in a specific memory area (instead of the heap, where standard new operator allocates memory). This may be shared memory or so... "Placement new" is one of the few situations where the object destructor can/must be called explicitely, i.e.: item[i]->~ITEM()