Today, I was told that “in our program, only use smart pointer when pointer is necessary”. I got confused at the very beginning and felt that it was another “code of coding” in company. However, when I dug more into it, I found it’s really a great practice to use it everywhere. Here is what I got.
Life is short, will make definition shorter too.
In a word, smart pointer is a wrapper of raw pointer in C++ with benefits:
- Taking care of dirty works, memory management
- Abstract pointer management in an object (more Java-like)
- Automatically avoid dangling pointer, memory leaking, etc.
When to use
When writing code where memory management is needed - Almost everywhere except when parameter needs a raw pointer.
How to use
For std C++, use either one of
std::weak_ptr. About difference.
Luckily, in QT, I got
QSharedPointer. It’s a built-in QT class designed to be a smart pointer wrapper. It has various methods to encapsulate and expose raw pointer inside, and it’s syntactically consistent with raw pointer, so it’s a very capable substitute.
qnam = QSharedPointer<QNetworkAccessManager>(new QNetworkAccessManager); connect(qnam.data(), SIGNAL(finished(QNetworkReply*)), this, SLOT(onReply(QNetworkReply*))); ... qnam->post(request, postData);
qnam is a smart pointer object which wraps a *QNetworkAccessManager and points to a new object as well. In second line, because
connect needs a raw pointer as parameter, use
QSharedPointer::data method to expose the raw pointer inside.
And as showed at last line, in syntax
QSharedPointer matches ordinary pointers. Great match.
Since smart pointer is such a powerful mechanism, which takes advantage of Java-like features, but keeps the versatility of C++, it should be used everywhere, at least in QT. If I can find the limit of it later, there will be another update!