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

C++11智能指针之shared_ptr

程序员文章站 2024-03-14 12:16:28
...

shared_ptr类似 Objective-C中的【引用概念】,这里分别测试了【引用增加】、【引用撤销】、【唯一性检查】,这里测试动作名称是自己随意叫的,现贴出测试代码及输出结果:

测试代码:

#include <windows.h>
#include <iostream>
#include <memory> // need include this header file

int main(void)
{

	std::shared_ptr<int> pInt(new int(5));

	std::cout << "---------------------" << std::endl;

	std::cout << *pInt << std::endl;
	std::cout << "pInt count :\t" << pInt.use_count() << std::endl;

	// check unique
	if (pInt.unique())
	{
		std::cout << "pInt [is] unique pointer to object " << std::endl;
	}
	else
	{
		std::cout << "pInt [is not] unique pointer to object " << std::endl;
	}

	std::shared_ptr<int> pInt2(pInt);

	std::cout << "---------------------" << std::endl;

	std::cout << "pInt count :\t" << pInt.use_count() << std::endl;
	std::cout << "pInt2 count :\t" << pInt2.use_count() << std::endl;

	// check unique
	if (pInt.unique())
	{
		std::cout << "pInt is unique pointer to object " << std::endl;
	}
	else
	{
		std::cout << "pInt [is not] unique pointer to object " << std::endl;
	}

	std::shared_ptr<int> pInt3(pInt);

	std::cout << "---------------------" << std::endl;

	std::cout << "pInt count :\t" << pInt.use_count() << std::endl;
	std::cout << "pInt2 count :\t" << pInt2.use_count() << std::endl;
	std::cout << "pInt3 count :\t" << pInt3.use_count() << std::endl;

	pInt2.reset();

	std::cout << "---------------------" << std::endl;

	std::cout << "after pInt2.reset()" << std::endl;

	std::cout << "pInt count :\t" << pInt.use_count() << std::endl;
	std::cout << "pInt2 count :\t" << pInt2.use_count() << std::endl;
	std::cout << "pInt3 count :\t" << pInt3.use_count() << std::endl;

	pInt2.reset();

	std::cout << "---------------------" << std::endl;

	std::cout << "after pInt2.reset()" << std::endl;

	std::cout << "pInt count :\t" << pInt.use_count() << std::endl;
	std::cout << "pInt2 count :\t" << pInt2.use_count() << std::endl;
	std::cout << "pInt3 count :\t" << pInt3.use_count() << std::endl;

	pInt3.reset();

	std::cout << "---------------------" << std::endl;

	std::cout << "after pInt3.reset()" << std::endl;

	std::cout << "pInt count :\t" << pInt.use_count() << std::endl;
	std::cout << "pInt2 count :\t" << pInt2.use_count() << std::endl;
	std::cout << "pInt3 count :\t" << pInt3.use_count() << std::endl;

	// check unique
	if (pInt.unique())
	{
		std::cout << "pInt is unique pointer to object " << std::endl;
	}
	else
	{
		std::cout << "pInt [is not] unique pointer to object " << std::endl;
	}

	system("pause");

	return 0;
}
输出结果如下图所示:

C++11智能指针之shared_ptr
其它可参考链接:http://blog.csdn.net/xiejingfa/article/details/50750037

相关标签: shared_ptr