Note that there are some explanatory texts on larger screens.

plurals
  1. POSmart references in C++
    primarykey
    data
    text
    <p>Edit: Welp, I guess this was a terrible idea.</p> <p>Is it possible to make a smart reference in C++ (for a specific class, since you can't overload the . operator) with the same semantics as a normal C++ reference, but which is reseated when used in an STL container?</p> <p>For example, if I have some <code>int_ref</code> class with the normal integer operators overloaded, and construction and assignment looks like this:</p> <pre><code>class int_ref{ int * p; public: int_ref(int * ip) : p(ip) {} int_ref(const int_ref &amp; other) : p(other.p) { /* maybe some refcounting stuff here */ } int_ref &amp; operator = (const int_ref &amp; other){ if (!p) throw something_bad(); *p = *other.p; return *this; } void reseat(const int_ref &amp; other){ p = other.p; } } </code></pre> <p>Then I can't use this with <code>std::vector</code> since it won't reseat the references, and I don't want this kind of thing:</p> <pre><code>std::vector&lt;int_ref&gt; vec; int_ref five = new int(5); vec.push_back(five); vec.push_back(new int(1)); std::sort(vec.begin(), vec.end()); // the value of five is now 1 </code></pre> <p>I can use rvalue references to make it play nice with the STL,</p> <pre><code>int_ref &amp; operator=(int_ref &amp;&amp; other){ reseat(other); return *this; } </code></pre> <p>But then a function that returns an <code>int_ref</code> would use the rvalue overload, and I'd get this:</p> <pre><code>int_ref make_number(){ return new int(10); } int_ref ref = new int(5); int_ref other = ref; other = make_number(); // instead of copying, as a reference would, // other now points to something other than ref </code></pre> <p>Is there a way around this? Is this just a terrible idea in general?</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