2017年2月24日 星期五

05 C++ My Notes (TBC)

05 C++ My Notes

When to use dynamic_cast?
Use dynamic_cast for polymorphic downcasting that would check type correctness at runtime with performance overhead, and return nullptr of type of castee is not compatible for the target type for pointer castee, or an bad_cast exception will be thrown for reference castee.

When to use static_cast?
Use it whenever possible to perform static checking by compiler to make sure type is compatible. Use it for upcast. Valid but dangerous to perform static downcast because may generate undefined behavior.

When to use reinterpret_cast?
It is the same as C style cast and should seldom be used.

When to use const_cast?
Scott Meyers said a good use of const_cast is to avoid code duplication by implementing the non-const member function in terms of const member function by first static casting the object itself as a const object to call the const member function, and then const cast away the const return type to non const type, i.e. T& get() {return const_cast<T&>(static_cast<const C&>(*this).get());


沒有留言:

張貼留言

2023 Promox on Morefine N6000 16GB 512GB

2023 Promox on Morefine N6000 16GB 512GB Software Etcher 100MB (not but can be rufus-4.3.exe 1.4MB) Proxmox VE 7.4 ISO Installer (1st ISO re...