C++ unique_ptr notes

Reprinted in unique_ptr

C++11 introduced the unique_ptr smart pointer, which is mainly used to replace the unsafe auto_ptr.
Therefore, the unique_ptr template class in the C++11 standard does not provide a copy constructor, only a move constructor.

std::unique_ptr<int> p1(new int);
std::unique_ptr<int> p2(p1);//错误,堆内存不共享
std::unique_ptr<int> p2(std::move(p1));//正确,调用移动构造函数

For p1 and p2 that call the move constructor, p2 will take ownership of the heap space pointed to by p1, and p1 will become a null pointer (nullptr). Is it similar to the copy constructor of auto_ptr?

Member methods provided by the unique_ptr template class
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41363459/article/details/115006788