Wrote a lot about vector blog, in fact, vector is very convenient, but also very simple. But many of the error-prone problems are caused by the smart pointers of the elements in the vector. So decided to start writing a story about smart pointers, especially the unique_ptr pointers.
This is a start, let's use std::unique_ptr instead of new operator!
or using a program to speak:
#include<iostream>int main(){ while (true) intnewint;}
Look at the memory in Task Manager:
At this point, use the smart pointer unique_ptr:
#include<iostream>#include<memory>int main(){ while (true) std::unique_ptr<int> x(newint(10));}
Two pictures can clearly see the benefits of smart pointers.
If we release the traditional pointers in time, we can also achieve the effect of smart pointers:
#include <iostream>usingnamespacestd;int main() { while (true) { intnewint; delete x; } return0;}
Here's another mistake, the C + + code written on the Mac editor, which uses the smart pointer unique_ptr, when the code is in vs2015, it prompts for an error:
' Unique_ptr ' is not a member of ' STD '
The reason is very simple, is missing unique_ptr header file:
#include<memory>
So you might be wondering when the smart pointer frees up memory?
Unique_ptr objects automatically delete the object they manage (using a deleter) as soon as they themselves is Destro Yed, or as soon as their value changes either by a assignment operation or by a explicit call to Unique_ptr::reset.
The next one will start with the Unique_ptr constructor!!
Real-Life Smart pointer Unique_ptr series in C + +-use std::unique_ptr instead of new operator (Error: ' Unique_ptr ' is not a member of ' STD ')