C++ 智能指针

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()
{
   
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值