此只能指针已经被纳入C++11,只因它实在是我们太需要它了!
如下的这些方面是我们需要它的理由
(1)引用计数让你摆脱delete的使用,只要有一个指针对象没有被析构,管理的对象就不会被析构,所以你可以按值传递给函数,按值从函数返回
(2)提供了变参工厂函数:make_shared<T>(...),让你摆脱new的出现
(3)获取原始指针的成员函数:get(),可以让你在需要原始指针的地方向外部提供,原始指针,如同string的成员函数:c_str()
(4)可以放在容器中管理对象
(5)可以实现桥接模式、工厂模式等,是很多设计模式实现的关键
(6)你仅仅需要学习它,使用它
(8)自定义删除行为,参考博客,可以针对FILE*的fclose进行快速定制、
(9)经典适用场景,来自于《C++ Primer》shared_ptr章节的示例
引用计数与释放
#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
请按任意键继续. . .
std::make_shared()与派生
下面的例子展示了构造派生类对象交给基类智能指针的情形,从而彻底避免了new的出现:
#include<iostream>
#include <memory>
using namespace std;
class Base
{
public:
Base(void);
virtual ~Base(void);
virtual void f(void) = 0;
};
Base::Base(void)
{
std::cout << "Base::Base(void)" << std::endl;
}
Base::~Base(void)
{
std::cout << "Base::~Base(void)" << std::endl;
}
class Drived : public Base
{
public:
Drived(void);
~Drived(void);
void f(void);
};
Drived::Drived(void)
{
std::cout << "Drived::Drived(void)" << std::endl;
}
Drived::~Drived(void)
{
std::cout << "Drived::~Drived(void)" << std::endl;
}
void Drived::f(void)
{
std::cout << "void Drived::f(void)" << std::endl;
}
int main()
{
std::shared_ptr<Base> spBase = std::make_shared<Drived>();
spBase->f();
return 0;
}
另外参考应用:
相关资源:http://www.cnblogs.com/TianFang/archive/2008/09/19/1294521.html