智能指针与堆内存管理

本文介绍了C++11中的智能指针,包括shared_ptr、weak_ptr和unique_ptr的用法及注意事项。重点讲解了智能指针如何初始化、如何避免内存管理陷阱,如多个shared_ptr管理同一内存、智能指针与原始指针转换等问题,并提到了弱引用在解决循环引用问题中的作用。
摘要由CSDN通过智能技术生成

 

目录

shared_ptr

std::weak_ptr

std::unique_ptr

使用时注意事项:

①.new的普通指针与shared_ptr转换:

②.指向栈的指针与shared_ptr转换:

3.智能指针向常规指针的转换


自从c++11引入智能指针shared_ptr后,我们似乎再也不用担心new的内存没有释放之类的问题了,但是也带来了其他的问题。

shared_ptr

智能指针是指向动态分配(堆)对象的指针,用于生存期控制,能确保自动正确的销毁动态分配的对象,防止内存泄露。它的一种通用实现技术是使用引用计数。每次使用它,内部引用计数加1,每析构一次,内部引用计数减1,减为0时,删去所指向的堆内存。

C++11中的智能指针包括:

std::shared_ptr

std::unique_ptr

std::weak_ptr

其中最常用的就是std::shared_ptr。每个shared_ptr的拷贝都指向相同的内存.最后一个shared_ptr析构的时候,堆中的内存才会被释放。share_ptr类型的对象具有获得指针所有权并共享所有权的能力。

初始化:

可以通过指针来初始化它:template <class U> explicit shared_ptr (U *p);

std::shared_ptr<int>p(new int(2));

std::shared_ptr<int>p2= p;

std::shared_ptr<BaseConnector> m_connt = make_shared<Connector>(m_ios, m_strIP, m_port);

通过构造函数、赋值函数或者 make_shared 函数初始化智能指针。

例子:

// shared_ptr constructor example
#include <iostream>
#include <memory>

struct C {int* data;};

int main () {
  std::shared_ptr<int> p1;
  std::shared_ptr<int> p2 (nullptr);
  std::shared_ptr<int> p3 (new int);
  std::shared_ptr<int> p4 (new int, std::default_delete<int>());
  std::shared_ptr<int> p5 (new int, [](int* p){delete p;}, std::allocator<int>());
  std::shared_ptr<int> p6 (p5);
  std::shared_ptr<int> p7 (std::move(p6));
  std::shared_ptr<int> p8 (std::unique_ptr<int>(new int));
  std::shared_ptr<C> obj (new C);
  std::shared_ptr<int> p9 (obj, obj->data);

  std::cout <
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值