Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><code>auto_ptr</code> doesn't behave the same way as a pointer in this respect. There are special rules in the language to allow <code>Shape*</code> to be static_cast to <code>Circle*</code> when <code>Circle</code> derives from <code>Shape</code>. The downcast is not entirely type-safe, since it relies on the user to provide a pointer value that actually does point to the <code>Shape</code> base class sub-object of a <code>Circle</code>, but the standard allows it for convenience. <code>auto_ptr</code> is "just" a library class, and has no equivalent conversion.</p> <p>Even if you could do it, it would often go wrong. When you copy an <code>auto_ptr</code>, the original loses ownership of the resource. Your <code>static_cast</code> would copy the <code>auto_ptr</code> to a temporary, and so <code>aS</code> would be reset and the resource would be destroyed when the temporary is (at the end of the expression). In your example that's fine, since it's going to be destroyed at <code>return</code> anyway, but generally speaking you don't want to copy <code>auto_ptr</code> except at a function call parameter or return value, to indicate transfer of ownership from caller to callee, or vice versa.</p> <p>What you can do instead is <code>static_cast&lt;Circle*&gt;(aS.get())-&gt;GetRadius()</code>, or better yet restructure your code to avoid the need for a downcast. If you know that your object is a <code>Circle</code>, keep it in an <code>auto_ptr&lt;Circle&gt;</code>[*]. If you keep it in an <code>auto_ptr&lt;Shape&gt;</code>, then don't rely on it being a <code>Circle</code>.</p> <p>[*] Or, if your implementation provides them, a better smart pointer such as <code>unique_ptr</code>, <code>scoped_ptr</code> or <code>shared_ptr</code>. Even if your implementation doesn't provide them, there's Boost.</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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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