1. shared_ptr : 智能指针。
2.转换: shared_ptr<std::exception> sp1 = (new bad_exception("error"));
shared_ptr<bad_exception>sp2 = dynamic_pointer_cast<bad_exception>(sp1);
3.shared_ptr<int>sp(new int(10)); //指向整数的 shared_ptr
shared_ptr<int> sp2 = sp; //
*sp2 = 100; //这时两个 *sp *sp2 都为100
4.make_shared #include <boost/make_shared.hpp>
shared_ptr<string>sp = make_shared<string>("make_shared");
shared_ptr<vector <int> > spv = make_shared<vector <int > >(10,2);
5.把 shared_ptr 放入标准的容器中 。
int main(){
typedef vector<shared_ptr<int> > vs;
vs v(10);
int i = 0;
for(vs::iterator pos = v.begin(); pos!= v.end(); ++pos){
(*pos) = make_shared<int> (++i);
}
shared_ptr<int> p = v[9];
*p = 100;
cout << *v[9] << endl;
}
6. class sample{
private:
class impl;
shared_ptr<impl>p;
public:
sample(); //构造函数
void print(); //接口
};
class sample::impl{
public:
void print(){cout << "impl print" << endl;}
};
sample::sample():p(new impl){} //构造函数 初始化
void sample::print(){ p-> print(); } //调用pimpl 实现print
桥接模式的使用
sample s ;
s.print();
7.使用 shared_ptr 管理资源 如socket shared_ptr(Y *p ,D d); D为删除器
socket_t *s = open_socket();
shared_ptr<socket_t> p(s,close_socket);
shared_ptr 离开作用域自动释放 socket
当然 当删除器中传入其他函数时 即实现 退出作用域 调用其他函数功能。
8. shared_array :
#include <boost/smart_ptr.hpp>
using namespace boost;
int main(){
int *p = new int[100];
shared_array<int> sa(p);
shared_array<int> sa2 = sa;
sa[0] = 10;
assert(sa2[0] = 10);
}
9 . weak_ptr
shared_ptr<int> sp(new int(10));
weak_ptr<int> wp (sp);
shared_ptr<int> sp2 = wp.lock(); // weak_ptr lock() 方法返回 shared_ptr 指针
10. 用 shared_ptr 管理自己
#include <boost/enable_shared_from_this.hpp>
#include <boost/make_shared.hpp>
class self_shared : public enable_shared_from_this<self_shared>{
public:
self_shared(int n):x(n){}
int x;
void print(){ cout<< "self_shared:" << x << endl; }
};
int main(){
shared_ptr<self_shared> sp = make_shared<self_shared>(314);
sp->print();
shared_ptr<self_shared> p = sp->shared_from_this();
p->x = 1000;
p->print();
}
//---------------错误---------------
int* a=new int(2);
shared_ptr<int>sp=a;// error
sp=a;// error
//----------正确用法 -------------
int* a=new int(2);
shared_ptr<int> sp(a);//构造函数
shared_ptr<int> sp1(sp);//copy构造
sp1 = sp; //赋值
就是不允许使用一个纯指针给一个智能指针赋值或copy构造。只能使用智能指针给另一个智能指针赋值或copy构造。
## 用 shared_ptr 包装 boost :: thread .
void simple_print(int * id){
for(int i = 0 ; i< 5; i++){
cout << *id << ":" << i << endl;
sleep(3);
}
}
int main(){
int forcin = 0;
vector <boost :: shared_ptr<boost::thread > > thread_pool;
for(int thread_num = 0; thread_num < 5 ; thread_num ++){
boost::shared_ptr<boost::thread> thread(new boost::thread(boost::bind(&simple_print,&thread_num)));
thread_pool.push_back(thread);
// thread->join();
sleep(2);
}
return 0;
}