Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>For me it seems quite acceptable solution if X's destructor will be called before placement new. It's syntactically allowed even the destructor is not actually specified for the class.</p> <pre><code>struct X { int val; int* pVal; X(int v) : val(v), pVal(&amp;val) {} }; X x(1); void foo() { doStuffWith(x); x.~X(); new (&amp;x) X(2); doStuffWith(x); } </code></pre> <p>In this form it is a correct way to reuse memory for any object (but only if the object's ctor can't throw! otherwise UB may happen on program shutdown, i.e. double call of the destructor).</p> <p>Indeed, the equality of pointers passed and returned from placement new in it non-array form is guaranteed by the standard:</p> <blockquote> <h3>18.6.1.3 Placement forms</h3> <p>...</p> <p>void* operator new(std::size_t size, void* ptr) noexcept;</p> <p>Returns: ptr.</p> <p>Remarks: Intentionally performs no other action.</p> </blockquote> <p>(and the result of the conversion to void* and then back to the same pointer type is also guaranteed to be the same as the source pointer)</p> <p>However, to avoid non-proper use of the class it would be more safe either define copy assignment and copy constructor or declare this class as noncopyable (with deleted ones)</p> <p>And only the last (noncopyable) case may be regarded as a reason for using placement new.</p> <p>Although I'm far from promoting placement new for general use, it express the intention to reuse object memory directly and doesn't rely on any optimization. Copy constructor and copy assignment are, of course, more safe, but don't express this intention excactly: no "copy" actually needed, the new object should be constructed in place of the old one.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload