I was reading this article and I came across the following definition (in qglobal.h):
template <typename T> static inline T *qGetPtrHelper(T *ptr) { return ptr; }
template <typename Wrapper> static inline typename Wrapper::pointer qGetPtrHelper(const Wrapper &p) { return p.data(); }
#define Q_DECLARE_PRIVATE(Class) \
inline Class##Private* d_func() { return reinterpret_cast<Class##Private *>(qGetPtrHelper(d_ptr)); } \
inline const Class##Private* d_func() const { return reinterpret_cast<const Class##Private *>(qGetPtrHelper(d_ptr)); } \
friend class Class##Private;
I understand that the macro defines common functions for classes that utilize the D-pointer/pImpl pattern. However I don't quite grasp the need for the qGetPtrHelper
function. It just returns a copy of a pointer that will be casted right away. Couldn't the ptr
variable casted directly without this function?
d_ptr can be a smart pointer (QScopedPointer, for instance) and in that case it can't be just passed to reinterpret_cast: d_func() would have to access the internal pointer using a member function or so requiring two versions of the macro (in fact, there used to be two before qGetPtrHelper existed). What qGetPtrHelper does is to trigger an implicit cast of a smart pointer, when passed as the argument, to a raw one, thus eliminating the need for special handling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With