c++笔记-智能指针

智能指针

#include <memory>
void deleteInt(int* p)
{
	delete[] p;
}

int main()
{
	std::shared_ptr<int> p1;
	std::shared_ptr<int> p2(nullptr);
	std::shared_ptr<int> p3(new int(10)); //初始化赋值为10,而不是十个int大小的内存
	std::shared_ptr<int> p4 = std::make_shared<int>(10);
	std::shared_ptr<int> p5(p4); //拷贝构造1
	std::shared_ptr<int> p6 = p5; //拷贝构造2
	std::shared_ptr<int> p7(std::move(p6)); //移动构造1
	std::shared_ptr<int> p8 = std::move(p7);
	//初始化智能指针,数组,并自定义释放规则
	std::shared_ptr<int> p9(new int[100], [](int* p) {delete[]p; });
	std::shared_ptr<int> p10(new int[100], deleteInt);
	std::shared_ptr<int> t1(new int(19));
	std::shared_ptr<int> t2(t1);
	std::cout << "*t1:" << *t1 << std::endl;
	std::cout << "*t2:" << *t2 << std::endl;
	t1.reset();
	if (t1)
	{
		std::cout << "t1不为空";
	}
	else
	{
		std::cout << "t1为空";
	}
	std::cout << std::endl;
	//std::cout << "*t1:" << *t1 << std::endl;
	std::cout << "t1.use_count:"<< t1.use_count() << std::endl;
	std::cout << "*t2:" << *t2 << std::endl;
	std::cout <<"t2.use_count:"<< t2.use_count() << std::endl;
	cin.get(); //输入enter键才会退出程序
	    return 0;
}
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页