您的位置:首页 > 编程语言 > C语言/C++

C++内存管理利器shared_ptr V2.0

2014-03-02 20:41 330 查看
此只能指针已经被纳入C++11,只因它实在是我们太需要它了!

如下的这些方面是我们需要它的理由

(1)引用计数让你摆脱delete的使用,只要有一个指针对象没有被析构,管理的对象就不会被析构,所以你可以按值传递给函数,按值从函数返回

(2)提供了变参工厂函数:make_shared<T>(...),让你摆脱new的出现

(3)获取原始指针的成员函数:get(),可以让你在需要原始指针的地方向外部提供,原始指针,如同string的成员函数:c_str()

(4)可以放在容器中管理对象

(5)可以实现桥接模式工厂模式等,是很多设计模式实现的关键

(6)你仅仅需要学习它,使用它

(7)为了防止循环引用而不能释放,需要借助weak_ptr

(8)自定义删除行为参考博客,可以针对FILE*的fclose进行快速定制、

(9)经典适用场景,来自于《C++ Primer》shared_ptr章节的示例

如果要使用boost的shared_ptr要知道与VS自带的那个shared_ptr避免冲突。

因为在VS的include目录下有一个全局的shared_ptr,所以应该像如下这样正规的使用boost的shared_ptr

boost的所有智能指针都在smart_ptr.hpp头文件中。

#include <vector>
#include <memory>
#include <iostream>
using namespace std;
class test;
typedef shared_ptr<test> test_ptr ;

class test
{
public:
test(){cout<<"a test object created"<<endl;}
~test(){cout<<"a test object destroyed"<<endl;}
void print(void) const {cout<<"test print"<<endl;}
};

void fun(const test_ptr& tp)
{
cout<<"fun begin"<<endl;
tp->print();
cout<<"fun end"<<endl;
}
int main()
{
test_ptr pt(new test());
vector<test_ptr> test_ptr_array;
for (int i=0;i<10;i++)
{
test_ptr_array.push_back(pt);
}
for (int i=0;i<10;i++)
{
test_ptr_array[i]->print();
}
fun(pt);
return 0;
}


a test object created

test print

test print

test print

test print

test print

test print

test print

test print

test print

test print

fun begin

test print

fun end

a test object destroyed

请按任意键继续. . .

 

#include <string>
#include <iostream>
#include <boost/shared_ptr.hpp>

class implementation
{
public:
~implementation() { std::cout <<"destroying implementation\n"; }
void do_something() { std::cout << "did something\n"; }
};

void test()
{
boost::shared_ptr<implementation> sp1(new implementation());
std::cout<<"The Sample now has "<<sp1.use_count()<<" references\n";

boost::shared_ptr<implementation> sp2 = sp1;
std::cout<<"The Sample now has "<<sp2.use_count()<<" references\n";

sp1.reset();
std::cout<<"After Reset sp1. The Sample now has "<<sp2.use_count()<<" references\n";

sp2.reset();
std::cout<<"After Reset sp2. The Sample now has "<<sp2.use_count()<<" references\n";
}

void main()
{
test();
}
The Sample now has 1 references

The Sample now has 2 references

After Reset sp1. The Sample now has 1 references

destroying implementation

After Reset sp2. The Sample now has 0 references

请按任意键继续. . .

另外参考应用:

相关资源:http://www.cnblogs.com/TianFang/archive/2008/09/19/1294521.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: