Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to implement smart pointer which can be instantiated with void?
    primarykey
    data
    text
    <p>Some smart pointer templates, such as boost::shared_ptr, may be instantiated with void to hold an arbitrary object:</p> <p><a href="http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/sp_techniques.html#pvoid" rel="nofollow noreferrer">http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/sp_techniques.html#pvoid</a></p> <p>Below is a minimal scoped_ptr implementation. When instantiated with void, the compiler complains about an illegal "reference to void" being formed in the dereference operator. It seems the "substitution failure is not an error" (SFINAE) rule does not cover this situation. </p> <p>How then is it possible to implement a scoped_ptr? In particular, is there an alternative to writing a template specialization? This would cause large code reduplication with a realistic smart pointer implementation.</p> <pre><code>#include &lt;cstdlib&gt; template&lt;typename T&gt; void destroy(T* ptr) { delete ptr; } class scoped_ptr_impl_base { public: virtual ~scoped_ptr_impl_base() { } }; template&lt;typename T, typename F&gt; class scoped_ptr_impl : public scoped_ptr_impl_base { public: scoped_ptr_impl(T* ptr, F dtor) : m_ptr(ptr), m_dtor(dtor) { } virtual ~scoped_ptr_impl() { m_dtor(m_ptr); } private: T* m_ptr; F m_dtor; }; template&lt;typename T&gt; class scoped_ptr { public: explicit scoped_ptr(T* ptr = 0) : m_ptr(ptr), m_impl(new scoped_ptr_impl&lt;T, void (*)(T*)&gt;(&amp;destroy&lt;T&gt;)) { } template&lt;typename F&gt; scoped_ptr(T* ptr, F dtor) : m_ptr(ptr), m_impl(new scoped_ptr_impl&lt;T, F&gt;(ptr, dtor)) { } ~scoped_ptr() { delete m_impl; } T&amp; operator*() { return *m_ptr; } T* operator-&gt;() { return m_ptr; } private: T* m_ptr; scoped_ptr_impl_base* m_impl; scoped_ptr(const scoped_ptr&amp;); scoped_ptr&amp; operator=(const scoped_ptr&amp;); }; int main() { scoped_ptr&lt;void&gt; p(std::malloc(1), std::free); // scoped_ptr.cpp: In instantiation of `scoped_ptr&lt;void&gt;': // scoped_ptr.cpp:76: instantiated from here // scoped_ptr.cpp:56: error: forming reference to void // (g++ 4.3.3) return 0; } </code></pre>
    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.
    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