c+智能指针源码分析_C ++中的智能指针

c+智能指针源码分析

In this article, we’ll take a look at how we can use Smart Pointers in C++.

在本文中,我们将研究如何在C ++中使用智能指针

Smart Pointers are an abstract interface to actual pointers (also called raw pointers), but with the additional benefit of automatically managing resources and freeing memory.

智能指针是实际指针(也称为原始指针 )的抽象接口,但具有自动管理资源和释放内存的其他好处。

Smart Ptr Example
Smart Ptr Example
Smart Ptr示例

The design logic for a smart pointer is to implement it as a class.

智能指针的设计逻辑是将其实现为类。

This is because a class has a destructor, which will trigger automatically when an object is at the end of its scope. Smart Pointers use the destructors to free up resources automatically.

这是因为类具有析构函数 ,当对象位于其作用域的末尾时,它将自动触发。 智能指针使用析构函数自动释放资源。

You don’t need to free smart pointers explicitly, and hence they are “smart” pointers since they know when they need to free resources.

您无需显式释放智能指针,因此它们是“智能”指针,因为它们知道何时需要释放资源。

Let’s understand more about these types of smart pointers in C++, using examples.

通过示例,让我们更多地了解C ++中的这些智能指针类型。



在C ++中使用智能指针 (Using Smart Pointers in C++)

These pointers are defined in the standard C++ library, in the std namespace. To include some of these pointers, we also need the <memory> header file.

这些指针是在标准C ++库的std名称空间中定义的。 要包括其中一些指针,我们还需要<memory>头文件。

There are three commonly used smart pointers, called:

有三种常用的智能指针,称为:

  • unique_ptr

    unique_ptr
  • shared_ptr

    shared_ptr
  • weak_ptr

    weak_ptr

Let’s go through them one by one.

让我们一一介绍。



unique_ptr – C ++中的智能指针 (unique_ptr – Smart pointer in C++)

This is a smart pointer that will only permit one owner of the pointer. That is, unique_ptr can contain, at maximum, only a single raw pointer (“unique” pointer) that points to a single memory location.

这是一个智能指针,将只允许该指针的一个所有者。 也就是说, unique_ptr最多只能包含一个指向单个内存位置的原始指针 (“唯一”指针)。

Keep this as your default choice, unless you’re working with multiple threads, or whenever you need multiple owners to the same raw pointer.

除非您正在使用多个线程,或者需要多个所有者使用同一原始指针,否则请将其保留为默认选择。

To create a smart pointer using unique_ptr, there are two ways of achieving this:

要使用unique_ptr创建智能指针,有两种方法可以实现:

情况1:从对象创建唯一的智能指针 (Case 1: Creating a Unique Smart Pointer from an object)

If you have an object and want to create a smart pointer in C++ which points to this object, use the below syntax:

如果您有一个对象,并且想要在C ++中创建指向该对象的智能指针&#

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值