Effective Modern C++:unique_ptr
You should include
unique_ptr
Just as its name means, unique_ptr guarantees that there is only one pointer point to a specific memory block. So it cannot be copied by only moved.
Init a unique_ptr
unique_ptr<int> p{ new int };
unique_ptr<int> p{ new int{4} };
As you can see, smart pointers are wraps of normal pointers, we call them “raw” pointers.
move a unique_ptr
unique_ptr<int> q = p; //wrong, copy is not allowed
unique_ptr<int> q = move(p);//move p to q
if (p == nullptr)
cout << "p is null now\n";
unique_ptr can only be moved, when the original unique_ptr is moved to another one, the original unique_ptr will be equal to nullptr.
delete a unique_ptr
p.release();
delete is not supported, you should use its “release” method.
use unique_ptr for factory pattern
unique_ptr<int> createnew(){
return unique_ptr<int>{new int{4}};
}//produce a unique_ptr
when you return a unique_ptr in a function, it is actually use its move method implicitly. So the unique_ptr is cleanly produced that you get the original, unique pointer.
What’s more, an unique_ptr can be moved to a shared_ptr!
unique_ptr<int> q{ new int{4} };
shared_ptr<int> s = move(q);
That means you can do the following:
shared_ptr<int> createnewShared(){
return unique_ptr<int>{new int{ 4 }};
}//produce a shared_ptr
if you want to produce a shared_ptr, the original version as an unique_ptr is moved, which means the newly produced shared_ptr will be the only existed copy of the original version, this is very clean.
If you want to use unique_ptr for array, you should declare it as:
int n = 5;
unique_ptr<int[]> intArray{ new int[n] };
for (int i = 0; i < n; i++)
intArray[i] = i;