Is Nokia misusing static_cast?

I just came across this example :

Scroll down to the bottom of the page where you will find

QWidget *pw = static_cast<QWidget *>(parent); 

The parent is of type: QObject, which is the QWidget base class, so in this case isnt: dynamic_cast should be used?

eg:

 QWidget *pw = dynamic_cast<QWidget*>(parent) 

Thanks,

+6
c ++ casting pointers qt
source share
6 answers

If you know that you are casting from the database to the descendant class (i.e., you know that the object is actually an instance of the descendant class), then static_cast is completely legal (and more efficient).

+8
source share

No, if parent has a QWidget* runtime type, then static_cast<QWidget*>(parent) is clearly defined and does what you expect. If it is not, then the behavior is undefined.

Contrast with dynamic_cast , which has always determined behavior, but is less efficient since it should use information such as runtime.

A good way to safely reinstall in debug mode and quickly in release mode is, for example:

 template <typename T, typename U> T* down_cast(U* x) { #ifdef NDEBUG return static_cast<T*>(x); #else return &dynamic_cast<T&>(*x); // Thanks @Martin #endif } 

used as follows:

 QWidget* w = down_cast<QWidget*>(parent); 
+8
source share

Since you are explicitly requesting the wrong use: the opposite is true, it would be wrong to use dynamic_cast here.

While both are legal, dynamic_cast indicates that you (the programmer) are not sure that the cast will succeed, and you are expected to check the result of the cast to verify success. When you are sure that the throw will be successful, then this is very misleading. Therefore, use static_cast . This indicates that the types are always well known and that the result of the throw is likely to succeed.

+2
source share

As long as you can make sure that the parent must actually be a QWidget or a derived type of QWidget, static_cast does a great job and gives you additional information that you will lose with dynamic_cast.

So you can see it as additional documentation - obviously, only assuming that people who write the code know what they are doing (we will give them the opportunity to doubt;))

0
source share

There is no "should be." Both will work just fine. The reason for using dynamic_cast here would be if you wanted to do a conversion runtime check. But the author of the code did not feel that he needed a run-time check, so dynamic_cast was not needed.

In fact, dynamic_cast rarely required because in most cases static_cast will do the job. Just like a sanity check, it might have added a statement with dynamic_cast , but not as a primary casting method.

0
source share

Usually, but if your code can know that the source object is a QWidget (perhaps through some other flag), you can save time and do static_cast . Use with caution.

0
source share

All Articles