Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>"Alexandrescu avoids this problem in his library Loki by having accessor functions for the encapsulated pointer, but I'd prefer not to give direct access to the raw pointer if possible"</p> <p>I think the cost of adding a raw pointer getter is going to be much less than the complexity cost of trying to get around not having raw access. There just isn't a language mechanism to convert instances between two unrelated template classes. To the compiler they are two completly different things with no relationship at run time. That's why you one template class instance can't access the others privates.</p> <p>You could consider creating such a relationship with a base class for all CountedPointers. You might have to put a void* in this base class. Then you'd have to do all the checking yourself (is T derrived from U then force the cast... Can I implicitly convert a T to a U?, if so force a conversion.. etc) but that may get pretty complex. Here's a rough start for this approach:</p> <pre><code>class CountedPointerBase { void* rawPtr; }; template &lt;class T&gt; class CountedPointer : public ConutedPointerBase { T* myRawT = reinterpret_cast&lt;T*&gt;(rawPtr); template&lt;class U&gt; CountedPointer( CountedPointer&lt;U&gt; u) { // Copying a CountedPointer&lt;T&gt; -&gt; CountedPointer&lt;U&gt; if (dynamic_cast&lt;U*&gt;(myRawT) != NULL) { // Safe to copy one rawPtr to another } // check for all other conversions } } </code></pre> <p>There may be a lot of other complexities in seeing if two types are compatible. Maybe there's some Loki/Boost template slickness that can determine for two type arguments if you could cast one to another.</p> <p>Anyway, as you can see, this might be a much more complex solution then just adding a getter. Being able to get the raw pointer has other benefits also. You can pass raw pointers into library functions that only accept raw pointers, and use them as temporaries, for example. It can be dangerous, I suppose, if someone on your team decides to hold onto a copy of the raw pointer as opposed to the smart ptr. That person should probably be summarily trout slapped.</p>
 

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