智能指针与内存管理

  1. std::shared_ptr
    std::shared_ptr 是一种智能指针,它能够记录多少个 shared_ptr 共同指向一个对象,从而消除显式的调用 delete,当引用计数变为零的时候就会将对象自动删除。

但还不够,因为使用 std::shared_ptr 仍然需要使用 new 来调用,这使得代码出现了某种程度上的不对称。

std::make_shared 就能够用来消除显式的使用 new,所以std::make_shared 会分配创建传入参数中的对象, 并返回这个对象类型的std::shared_ptr指针。例如:

std::shared_ptr 可以通过 get() 方法来获取原始指针,通过 reset() 来减少一个引用计数, 并通过use_count()来查看一个对象的引用计数。例如:

#include <iostream>
#include <memory>

void foo(std::shared_ptr<int> i)
{
	(*i)++;
}

int main() 
{
	auto pointer = std::make_shared<int>(10);
	foo(pointer);
	std::cout << *pointer << std::endl;

	auto pointer2 = pointer;
	auto pointer3 = pointer;
	int *p = pointer.get();

	std::cout << "pointer.use_cout() = " << pointer.use_count() << std::endl;
	std::cout << "pointer2.use_cout() = " << pointer2.use_count() << std::endl;
	std::cout << "pointer3.use_cout() = " << pointer3.use_count() << std::endl;

	pointer2.reset();
	std::cout << "pointer.use_cout() = " << pointer.use_count() << std::endl;
	std::cout << "pointer2.use_cout() = " << pointer2.use_count() << std::endl;
	std::cout << "pointer3.use_cout() = " << pointer3.use_count() << std::endl;

	pointer3.reset();
	std::cout << "pointer.use_cout() = " << pointer.use_count() << std::endl;
	std::cout << "pointer2.use_cout() = " << pointer2.use_count() << std::endl;
	std::cout << "pointer3.use_cout() = " << pointer3.use_count() << std::endl;

	return 0;
}

  1. unique_ptr
    std::unique_ptr 是一种独占的智能指针,它禁止其他智能指针与其共享同一个对象,从而保证代码的安全:
std::unique_ptr<int> pointer = std::make_unique<int>(10); // make_unique 从 C++14 引入
std::unique_ptr<int> pointer2 = pointer; // 非法

既然是独占,换句话说就是不可复制。但是,我们可以利用 std::move 将其转移给其他的 unique_ptr,例如:

#include <iostream>
#include <memory>

struct Foo {
	Foo() { std::cout << "Foo::Foo" << std::endl; };
	~Foo() { std::cout << "Foo::~Foo" << std::endl; };
	void foo() { std::cout << "Foo::foo()" << std::endl; };
};

void f(const Foo&)
{
	std::cout << "f(const Foot&)" << std::endl;
}

int main() 
{
	std::unique_ptr<Foo> p1(std::make_unique<Foo>());
	if (p1)
	{
		p1->foo();
	}
	
		std::unique_ptr<Foo> p2(std::move(p1));
		if (p2)
		{
			p2->foo();
		}
		if (p1)
		{
			p1->foo();
		}
		p1 = std::move(p2);
		if (p2)
		{
			p2->foo();
		}
	
	
	if (p1)
	{
		p1->foo();
	}
}

3.week_ptr
std::weak_ptr 没有 * 运算符和 -> 运算符,所以不能够对资源进行操作,它的唯一作用就是用于检查 std::shared_ptr 是否存在,其 expired() 方法能在资源未被释放时,会返回 false,否则返回 true。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值