Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of qGetPtrHelper in this example?

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?

like image 384
Tamás Szelei Avatar asked Nov 04 '11 21:11

Tamás Szelei


1 Answers

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.

like image 197
Jakub Wieczorek Avatar answered Oct 20 '22 04:10

Jakub Wieczorek