gosom
gosom

Reputation: 1319

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)

Upvotes: 0

Views: 336

Answers (2)

shrike
shrike

Reputation: 4511

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()

Upvotes: 1

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

The above is potentially invalid. The new operator constructs each object in the array already. This is double construction (which can and probably will lead to errors for less than trivial types).

for(i=0;i<10;++i)
    items[i] = ITEM();

This just assigns a default constructed object to each entry in the array. This is as safe as the assignment operator is.

In general placement new is supposed to be used on raw memory.

Upvotes: 1

Related Questions