文章目录
1.std::auto_ptr
C++17 已经被移除了,不需要了解,也不应该使用。
2.std::unique_ptr
unique_ptr具有和raw pointer同样的size, 小巧且快速,同时unique_ptr排他性的独占资源,所以其不能被拷贝赋值,只支持move语义,是 move-only type
- 拷贝构造函数
- 拷贝赋值
在unique_ptr不能使用,取而代之得是std::move
unique_ptr安全使用的前提是保证自己能够正常析构,这样才能保证其管理的资源能够随之析构,so~
- unique_ptr 需要申请在栈上
- unique_ptr 可以作为类的成员函数,但此时首先必须保证该类可以正常析构!
#include <iostream>
#include <memory> // for std::unique_ptr
#include <utility> // for std::move
class Resource
{
public:
Resource() {
std::cout << "Resource acquired\n"; }
~Resource() {
std::cout << "Resource destroyed\n"; }
};
int main()
{
std::unique_ptr<Resource> res1{
new Resource{
} }; // Resource created here
std::unique_ptr<Resource> res2{
}; // Start as nullptr
std::cout << "res1 is " << (static_cast<bool>(res1) ? "not null\n" : "null\n");
std::cout << "res2 is " << (static_cast<bool>(res2) ? "not null\n" : "null\n");
// res2 = res1; // Won't compile: copy assignment is disabled
res2 = std::move(res1); // res2 assumes ownership, res1 is set to null
std::cout << "Ownership transferred\n";
std::cout << "res1 is " << (static_cast<bool>(res1) ? "not null\n" : "null\n");
std::cout << "res2 is " << (static_cast<bool>(res2) ? "not null\n" : "null\n");
return 0;
} // Resource destroyed here when res2 goes out of scope
通过
- ->
- *
可以访问unique_ptr所管理得资源,通过statc_cast(ptr) 可以判断unique_ptr是否管理有效得资源
C++14中,支持std::make_unique(),可以更安全、有效、简单的创建unique_ptr,推荐使用!
1.1 Return from a function
unique_ptr可以直接return by value, 在return时,会调用std::move 把指针管理的资源指向新的被赋值的指针!
注意:不要return unque_ptr的指针或者引用
std::unique_ptr<Resource> createResource()
{
return std::make_unique<Resource>();
}
int main()
{