placement-new

Destroy and then construct new object using the same variable

孤者浪人 提交于 2019-11-26 05:58:58
问题 Sometimes it\'s nice to start over. In C++ I can employ this following simple manoeuvre: { T x(31, Blue, false); x.~T(); // enough with the old x ::new (&x) T(22, Brown, true); // in with the new! // ... } At the end of the scope, the destructor will run once again and all seems well. (Let\'s also say T is a bit special and doesn\'t like being assigned, let alone swapped.) But something tells me that it\'s not always without risk to destroy everything and try again. Is there a possible catch

Array placement-new requires unspecified overhead in the buffer?

雨燕双飞 提交于 2019-11-25 23:47:05
问题 5.3.4 [expr.new] of the C++11 Feb draft gives the example: new(2,f) T[5] results in a call of operator new[](sizeof(T)*5+y,2,f) . Here, x and y are non-negative unspecified values representing array allocation overhead; the result of the new-expression will be offset by this amount from the value returned by operator new[] . This overhead may be applied in all array new-expressions , including those referencing the library function operator new[](std::size_t, void*) and other placement

What uses are there for “placement new”?

旧时模样 提交于 2019-11-25 21:36:46
问题 Has anyone here ever used C++\'s \"placement new\"? If so, what for? It looks to me like it would only be useful on memory-mapped hardware. 回答1: Placement new allows you to construct an object in memory that's already allocated. You may want to do this for optimization when you need to construct multiple instances of an object, and it is faster not to re-allocate memory each time you need a new instance. Instead, it might be more efficient to perform a single allocation for a chunk of memory