Note that there are some explanatory texts on larger screens.

plurals
  1. POstd::reference_wrapper<T> usage in a container
    primarykey
    data
    text
    <p>If I could I would remove all raw pointers <code>*</code> from my code, because using them may be not thread safe and intentions of the design are not clear (optional value, ownership, etc). Sometimes however it is not that easy to not use pointers. For example we tend to use pointers for a base type in a container of polymorphic types:</p> <pre><code>class A : noncopyable { ... }; class B : public A { ... }; std::vector&lt;A*&gt; v; v.emplace_back(new B); // temporary container for some operation std::vector&lt;A*&gt; selected; if(check()) selected.emplace_back(v.front()); </code></pre> <p>What can you say about above code? Who is the owner? Is it a shared ownership or not? It is why we should probably do that for <code>v</code>:</p> <pre><code>std::vector&lt;std::unique_ptr&lt;A&gt;&gt; v; v.emplace_back(make_unique&lt;B&gt;()); </code></pre> <p>Now it is clear that <code>v</code> owns the objects but I still do not like that <code>selected</code> has a raw pointer and makes my design not intuitive. Looking into Standard C++ library I think that there is only one type that could do the job - <a href="http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper" rel="noreferrer">std::reference_wrapper</a>:</p> <pre><code>std::vector&lt;std::unique_ptr&lt;A&gt;&gt; v; v.emplace_back(make_unique&lt;B&gt;()); // temporary container for some operation std::vector&lt;std::reference_wrapper&lt;A&gt;&gt; selected; if(check()) selected.emplace_back(*v.front()); </code></pre> <p>How do you feel about that code? Is it a good practice? I know that <code>std::ref()</code> and <code>std::cref</code> where meant to primarily work with templates, but it seems that here we can also use it to clearly state our design intent. The only problem I see is that I have to dereference <code>std::reference_wrapper</code> with <code>get()</code> and there are no <code>operator*()</code> or <code>operator-&gt;()</code> inside to have the same interface like in a container with <code>unique_ptr</code>. Should I write something similar on my own? Or maybe a reference_wrapper could be extended for such use case in future C++ versions? Please share your feedback.</p> <p>EDIT: I changed the code samples to maybe better show the intent.</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.
 

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