Note that there are some explanatory texts on larger screens.

plurals
  1. POPlacement new based on template sizeof()
    primarykey
    data
    text
    <p>Is this legal in c++11? Compiles with the latest intel compiler and appears to work, but I just get that feeling that it is a fluke.</p> <pre><code> class cbase { virtual void call(); }; template&lt;typename T&gt; class functor : public cbase { public: functor(T* obj, void (T::*pfunc)()) : _obj(obj), _pfunc(pfunc) {} virtual void call() { (_obj)(*_pfunc)(); } private: T&amp; _obj; void (T::*_pfunc)(); //edited: this is no good: //const static int size = sizeof(_obj) + sizeof(_pfunc); }; class signal { public: template&lt;typename T&gt; void connect(T&amp; obj, void (T::*pfunc)()) { _ptr = new (space) functor&lt;T&gt;(obj, pfunc); } private: cbase* _ptr; class _generic_object {}; typename aligned_storage&lt;sizeof(functor&lt;_generic_object&gt;), alignment_of&lt;functor&lt;_generic_object&gt;&gt;::value&gt;::type space; //edited: this is no good: //void* space[(c1&lt;_generic_object&gt;::size / sizeof(void*))]; }; </code></pre> <p>Specifically I'm wondering if <code>void* space[(c1&lt;_generic_object&gt;::size / sizeof(void*))];</code> is really going to give the correct size for c1's member objects (_obj and _pfunc). (It isn't).</p> <p>EDIT: So after some more research it would seem that the following would be (more?) correct:</p> <pre><code>typename aligned_storage&lt;sizeof(c1&lt;_generic_object&gt;), alignment_of&lt;c1&lt;_generic_object&gt;&gt;::value&gt;::type space; </code></pre> <p>However upon inspecting the generated assembly, using placement new with this space seems to inhibit the compiler from optimizing away the call to 'new' (which seemed to happen while using just regular '_ptr = new c1;'</p> <p>EDIT2: Changed the code to make intentions a little clearer.</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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