欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

shared_ptr基本用法

程序员文章站 2024-02-29 09:42:16
...

头文件

shared_ptr需要头文件
#include <memory>

声明方法

//way1
auto sp1 = std::make_shared<int>(5);

//way2
int* p1 = new int[3];
memset(p1, 0, sizeof(int) * 3);
std::shared_ptr<int> sp2(p1);

增加计数

被引用则会增加计数

std::shared_ptr<int> ptr2(sp2);//再次被引用则计数+1

在函数内改变计数,超过生命周期后计数会恢复,test函数内的p1析构了。

void test(int* ptr)
{
	std::shared_ptr<int> p1(ptr);
	int n = p1.use_count();
	std::cout << n << std::endl;
}

得到原指针

get()函数返回原指针

int* n3 = sp1.get();
std::cout << *(sp2.get()) << std::endl;

一个例子


#include "stdafx.h"
#include <iostream>
#include <memory>

void fun(std::shared_ptr<int> sp)
{
	std::cout << "fun: sp.use_count() == " << sp.use_count() << '\n';
}

void test(int* ptr)
{
	std::shared_ptr<int> p1(ptr);
	int n = p1.use_count();
	std::cout << n << std::endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
	auto sp1 = std::make_shared<int>(5);

	int* n3 = sp1.get();
	std::cout << *sp1 << '\n';;
	std::cout << "sp1.use_count() == " << sp1.use_count() << '\n';
	std::shared_ptr<int> p2(sp1);
	std::cout << "sp1.use_count() == " << sp1.use_count() << '\n';

	fun(sp1);
	fun(sp1);

	std::cout  <<"------------------"<< std::endl;
	std::cout << std::endl;
	int* p1 = new int[3];
	memset(p1, 0, sizeof(int) * 3);

	*p1 = 11;
	*(p1 + 1) = 22;
	*(p1 + 2) = 33;

	std::shared_ptr<int> sp2(p1);
	int n = sp2.use_count();
	std::cout << n << std::endl;

	std::shared_ptr<int> ptr2(sp2);
	n = ptr2.use_count();
	std::cout << n << std::endl;

	std::shared_ptr<int> ptr3 = sp2;
	n = ptr3.use_count();
	std::cout << n << std::endl;

	
	//std::cout << sp2 << std::endl;
	std::cout << *(sp2.get()) << std::endl;
	std::cout << *(sp2.get()+1) << std::endl;
	std::cout << *(sp2.get() + 2) << std::endl;
	return 0;
}


相关标签: c++ shared_ptr