C++11 shared_ptr智能指针

简介: C++11 shared_ptr智能指针

#include<iostream>
using namespace std;
#include<memory>
class test {
public:
  test(int no) {
    this->no = no;
    cout << "调用构造函数: " << no << endl;
  }
  ~test() {
    cout << "调用析构函数: " << no << endl;
  }
private:
  int no;
};

 

 

构造方式一:

shared_ptr<test>sp;
  shared_ptr<test>sp2(new test(1));
  //use_count :当前管控同一个对象的智能指针对象
  cout<<"sp.use_count:" << sp.use_count() << endl;//0
  cout<<"sp2.use_count:" << sp2.use_count() << endl;//1
  sp = sp2;
  cout << "----sp = sp2----" << endl;
  cout << "sp.use_count:" << sp.use_count() << endl;//2
  cout << "sp2.use_count:" << sp2.use_count() << endl;//2
  shared_ptr<test>sp3(sp);
  cout << "---shared_ptr<test>sp3(sp)---" << endl;
  cout << "sp.use_count:" << sp.use_count() << endl;//3
  cout << "sp2.use_count:" << sp2.use_count() << endl;//3
  cout << "sp3.use_count:" << sp3.use_count() << endl;//3
  //sp.use_count() == sp2.use_count() == sp3.use_count()
  system("pause");

结果:

构造方式二: C++17之后支持

//数组对象管理
  shared_ptr<test[]>arr(new test[5]{ 11, 22, 33, 44, 55 });

结果:

构造方式三:

//仿函数
class DestructTest {
public:
  void operator()(test* t) {
    cout << "调用DestructTest... " << endl;
    delete t;
  }
};
shared_ptr<test>sp(new test(666), DestructTest());

 

使用make_shared初始化对象,分配内存效率更高

//使用make_shared初始化对象,分配内存效率更高
  // make_shared<类型>(参数)
  shared_ptr<string>s = make_shared<string>("ABC");
  shared_ptr<string>s2;
  s2 = make_shared<string>("abc");

主动释放对象:

//主动释放对象
  shared_ptr<string>s = make_shared<string>("ABC");
  s = NULL;
  //或
  // s = nullptr;

重置:

交换:

使用陷阱:shared_ptr作为被管控对象的成员时,小心因循环引用造成资源无法释放. (weak_ptr)

目录
相关文章
|
17天前
|
C++
C++(十八)Smart Pointer 智能指针简介
智能指针是C++中用于管理动态分配内存的一种机制,通过自动释放不再使用的内存来防止内存泄漏。`auto_ptr`是早期的一种实现,但已被`shared_ptr`和`weak_ptr`取代。这些智能指针基于RAII(Resource Acquisition Is Initialization)原则,即资源获取即初始化。RAII确保对象在其生命周期结束时自动释放资源。通过重载`*`和`-&gt;`运算符,可以方便地访问和操作智能指针所指向的对象。
|
17天前
|
C++
C++(九)this指针
`this`指针是系统在创建对象时默认生成的,用于指向当前对象,便于使用。其特性包括:指向当前对象,适用于所有成员函数但不适用于初始化列表;作为隐含参数传递,不影响对象大小;类型为`ClassName* const`,指向不可变。`this`的作用在于避免参数与成员变量重名,并支持多重串联调用。例如,在`Stu`类中,通过`this-&gt;name`和`this-&gt;age`明确区分局部变量与成员变量,同时支持链式调用如`s.growUp().growUp()`。
|
29天前
|
存储 安全 C++
C++:指针引用普通变量适用场景
指针和引用都是C++提供的强大工具,它们在不同的场景下发挥着不可或缺的作用。了解两者的特点及适用场景,可以帮助开发者编写出更加高效、可读性更强的代码。在实际开发中,合理选择使用指针或引用是提高编程技巧的关键。
23 1
|
1月前
|
安全 NoSQL Redis
C++新特性-智能指针
C++新特性-智能指针
|
1月前
|
编译器 C++
virtual类的使用方法问题之在C++中获取对象的vptr(虚拟表指针)如何解决
virtual类的使用方法问题之在C++中获取对象的vptr(虚拟表指针)如何解决
|
1月前
|
存储 C++
c++学习笔记06 指针
C++指针的详细学习笔记06,涵盖了指针的定义、使用、内存占用、空指针和野指针的概念,以及指针与数组、函数的关系和使用技巧。
29 0
|
1月前
|
安全 编译器 容器
C++STL容器和智能指针
C++STL容器和智能指针
|
1月前
|
C++
C++通过文件指针获取文件大小
C++通过文件指针获取文件大小
24 0
|
1月前
|
编译器 C语言 C++
【C++关键字】指针空值nullptr(C++11)
【C++关键字】指针空值nullptr(C++11)
|
1月前
|
算法 C++ 容器
【C++算法】双指针
【C++算法】双指针