Note that there are some explanatory texts on larger screens.

plurals
  1. POIs static_cast misused?
    text
    copied!<p>I have mixed feelings about <code>static_cast</code>, as it is the safest C++ cast available, but allows both safe and unsafe conversions at the same time, so you have to know the context to say if it is actually safe or might lead to UB (e.g. when casting to a sub-class).</p> <p>So why isn't there a safer explicit cast? Here is an example, where it could be useful. In COM, they have to return the interface pointer as <code>void** ppv</code>, so "have to" cast explicitely</p> <pre><code>*ppv = (IInterface*) this; </code></pre> <p>which was then suggested to be replaced by a safer C++ cast</p> <pre><code>*ppv = static_cast&lt;IInterface*&gt;(this); </code></pre> <p>But does it make sense to make even a <code>static_cast</code> here? <code>this</code> is of a class which derives from <code>IInterface</code>, so one could simply write</p> <pre><code>IInterface* p = this; // implicit conversion to base, safe for sure *ppv = p; </code></pre> <p>or use a helper like</p> <pre><code>template&lt;class T, class U&gt; T implicit_cast(U p) { return p; } *ppv = implicit_cast&lt;IInterface*&gt;(this); </code></pre> <p>So, is it true that <code>static_cast</code> is sometimes misused and can (should?) be replaced by this <code>implicit_cast</code> in some cases, or am I missing something?</p> <p>EDIT: I know that <a href="https://stackoverflow.com/questions/1742848/why-exactly-do-i-need-an-explicit-upcast-when-implementing-queryinterface-in-an">a cast is required in COM</a>, but it does not have to be <code>static_cast</code>, an implicit cast would be enough.</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