So when programming in Qt I like to go with the Qt implementation as far as possible.
As far as I've seen there's no Qt version of the std::unique_ptr
or is there?
What would be the alternatives that produce the "same" result in Qt if it doesn't exist?
std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.
In C++11 we can transfer the ownership of an object to another unique_ptr using std::move() . After the ownership transfer, the smart pointer that ceded the ownership becomes null and get() returns nullptr.
Creating a unique pointer as std::unique_ptr<T> myptr; doesn't allocate any memory, so you don't need to construct it and pass nullptr at all. So you can just create one and return it. nullptr is a keyword new in C++11 for better support of null pointers. unique_ptr can be constructed from nullptr , even implicitly.
auto ptr = make_unique<int>(); // Create a new unique_ptr object. auto ptr = make_unique<int>(); The dynamically allocated object is destroyed when the created unique pointer object is destroyed.
The Qt equivalent to std::unique_ptr
is QScopedPointer
.
It's significantly less useful as it doesn't support move semantics, making it closer in utility to C++03 std::auto_ptr
(Why is auto_ptr being deprecated?).
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