c++ unique_ptr和shared_ptr使用例子

2021/9/13 11:05:05

本文主要是介绍c++ unique_ptr和shared_ptr使用例子,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

std::unique_ptr不支持复制和赋值
std::shared_ptr支持复制和赋值

参考C++ 智能指针的正确使用方式 | 编程沉思录

#include <iostream>
#include <thread>

class PP {
public:
	PP(int v) { _v = v; }
	~PP() {
		printf("=== pp is end. _v: %d\n", _v);
	}
private:
	int _v = -1;

};


void fun0() {

	printf("begin of fun\n");
	std::vector<int *> a;

	for (int i = 0; i < 10; i++) {
		printf("%d\n", i);
		int *p = new int[1000 * 1000 * 10];
		memset(p , 0, 1000 * 1000 * 10);
		if (i == 5) {
			p[0] = 66;
			p[1] = 67;
			int x1 = p[0];
			int x2 = p[1];
			int x3 = p[2];
			printf("%d\n", x1);
			printf("%d\n", x2);
			printf("%d\n", x3);
		}
		a.push_back(p);
	}
	printf("%d\n", a[5][0]);
	printf("%d\n", a[5][1]);
	printf("sleep 2 seconds\n");
	std::this_thread::sleep_for(std::chrono::milliseconds(2000));
	printf("end of fun\n");
}


void fun1() {

	printf("begin of fun\n");
	std::vector<int *> a;

	for (int i = 0; i < 10; i++) {
		printf("%d\n", i);
		std::unique_ptr<int[]> p = std::make_unique<int[]>(1000 * 1000 * 10); // 不管是std::unique_ptr<int[]> p还是std::shared_ptr<int[]> p都会报错
		memset(p.get(), 0, 1000 * 1000 * 10);
		if (i == 5) {
			p[0] = 66;
			p[1] = 67;
			int x1 = p[0];
			int x2 = p[1];
			int x3 = p[2];
			printf("%d\n", x1);
			printf("%d\n", x2);
			printf("%d\n", x3);

		}
		a.push_back(p.get());
	}
	// 报错, 
	printf("%d\n", a[5][0]);
	printf("%d\n", a[5][1]);
	printf("sleep 2 seconds\n");
	std::this_thread::sleep_for(std::chrono::milliseconds(2000));
	printf("end of fun\n");
}


void fun2() {

	printf("begin of fun\n");
	std::vector<std::shared_ptr<int []>> a;
	std::vector<std::unique_ptr<PP>> b;
	//std::vector<std::shared_ptr<PP>> b;

	for (int i = 0; i < 10; i++) {
		printf("%d\n", i);
		//std::shared_ptr<int[]> p(new int[1000 * 1000 * 10]()); // c++17
		std::shared_ptr<int[]> p = std::make_unique<int[]>(1000 * 1000 * 10); // c++20
		memset(p.get(), 0, 1000 * 1000 * 10);
		if (i == 5) {
			p[0] = 66;
			p[1] = 67;
			int x1 = p[0];
			int x2 = p[1];
			int x3 = p[2];
			printf("%d\n", x1);
			printf("%d\n", x2);
			printf("%d\n", x3);

		}
		
		a.push_back(p);
		b.push_back(
			std::make_unique<PP>(i)
		);
	}
	printf("%d\n", a[5][0]);
	printf("%d\n", a[5][1]);
	printf("sleep 2 seconds\n");
	std::this_thread::sleep_for(std::chrono::milliseconds(2000));
	printf("end of fun\n");
}


int main()
{
	//fun0(); // 执行完毕返回main, 内存还没释放
	//fun1(); // 报错
	fun2(); // 执行完毕返回main, 内存已经释放
	printf("in main.\nSleep 2 seconds.\n");

	std::this_thread::sleep_for(std::chrono::milliseconds(2000));
	return 1;
}






 



这篇关于c++ unique_ptr和shared_ptr使用例子的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程