Note that there are some explanatory texts on larger screens.

plurals
  1. POAny reason to prefer static_cast over a chain of implicit conversions?
    primarykey
    data
    text
    <p>Suppose I have a class implementing several interfaces</p> <pre><code>class CMyClass : public IInterface1, public IInterface2 { }; </code></pre> <p>and in a member function of that class I need to obtain a <code>void*</code> pointer to one of those interfaces (typical situation in <a href="https://stackoverflow.com/questions/1742848/why-exactly-do-i-need-an-explicit-upcast-when-implementing-queryinterface-in-an"><code>IUnknown::QueryInterface()</code></a>.</p> <p>The typical solution is to use a <code>static_cast</code> to achieve pointer adjustment:</p> <pre><code>void* pointer = static_cast&lt;IInterface2*&gt;( this ); </code></pre> <p>and it is safe in this case if there's no known class inherited from <code>CMyClass</code>. But if such class exists:</p> <pre><code>class CDerivedClass : public CUnrelatedClass, public CMyClass {}; </code></pre> <p>and I accidentially do</p> <pre><code>void* pointer = static_cast&lt;CDerivedClass*&gt;( this ); </code></pre> <p>and <code>this</code> is actually a pointer to <code>CMyClass</code> instance the compiler won't catch me and the program might run into undefined behavior later - <code>static_cast</code> becomes unsafe.</p> <p>The suggested solution is to use implicit conversion:</p> <pre><code>IInterface2* interfacePointer = this; void* pointer = interfacePointer; </code></pre> <p>Looks like this will solve both problems - pointer adjustment and risk of invalid downcast.</p> <p>Are there any problems in the second solution? What could be the reasons to prefer the first one?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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