因为shared_ptr的构造需要new的调用,而用户往往会忽略delete的调用,从而引起重大错误。因此共享指针提供了工厂函数来包装new并消除显式的delete调用。
#include<iostream>
#include<boost/smart_ptr.hpp>
#include<boost/make_shared.hpp>
using namespace std;
using namespace boost;
void main()
{
shared_ptr<int> ps = make_shared<int>(10);//new delete隐藏在工厂函数中
cout<<*ps<<endl;
shared_ptr<string> ps1 = make_shared<string>("Hello Linux."); //new delete
cout<<ps1->size()<<endl;
}
make_shared()函数可以最多接受10个参数,然后把它们传递给类型T的构造函数,创建一个shared_ptr<T>的对象并返回。make_shared()函数要比直接创建shared_ptr对象的方式快且高效,因为它内部仅分配一次内存,消除了shared_ptr构造时的开销。