智能指针本质思想:
将堆对象的生存期用栈对象来管理,当new一个堆对象的时候,立刻用智能指针来接管,具体做法是在构造函数进行初始化(用一个指针指向堆对象),在析构函数中调用delete来释放堆对象。
由于智能指针本身是一个栈对象,它的作用域结束的时候,自动调用析构函数,从而调用了delete释放了堆对象。
scoped_ptr
#include <boost/scoped_ptr.hpp>
#include <iostream>
using namespace std;
class X
{
public:
X()
{
cout << "X ..." << endl;
}
~X()
{
cout << "~X ..." << endl;
}
};
int main(void)
{
cout << "Entering main ..." << endl;
{
boost::scoped_ptr<X> p(new X);
}
cout << "Exiting main ..." << endl;
return 0;
}
shared_ptr
#include <boost/shared_ptr.hpp>
#include <iostream>
using namespace std;
int main(void)
{
cout << "Entering main ..." << endl;
boost::shared_ptr<X> p1(new X);
cout << p1.use_count() << endl;
boost::shared_ptr<X> p2 = p1;
cout << p2.use_count() << endl;
p1.reset();
cout << p2.use_count() << endl;
p2.reset();
cout << "Exiting main ..." << endl;
return 0;
}
#include <boost/shared_ptr.hpp>
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
class X
{
public:
X()
{
cout << "X ..." << endl;
}
~X()
{
cout << "~X ..." << endl;
}
};
int main(void)
{
//vector<auto_ptr<X> > v;//auto_ptr<T>不能放置vector中
//auto_ptr<X> p(new X);
vector<boost::shared_ptr<X> >v;//shared_ptr<T>可以放置vector中
boost::shared_ptr<X> p(new X);
v.push_back(p);
cout<<p.use_count() << endl;
return 0;
}
weak_ptr
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
using namespace std;
class Parent;
class Child;
typedef boost::shared_ptr<Parent> parent_ptr;
typedef boost::shared_ptr<Child> child_ptr;
class Child
{
public:
Child() { cout << "Child ..." << endl; }
~Child(){ cout << "~Child ..." << endl; }
parent_ptr parent_;
};
class Parent
{
public:
Parent(){ cout << "Parent ..." << endl; }
~Parent(){ cout << "~Parent ..." << endl; }
boost::weak_ptr<Child> child_;//打破循环引用
};
int main(void)
{
parent_ptr parent(new Parent);//1
child_ptr child(new Child);//1
parent->child_ = child;//引用不加1
child->parent_ = parent;//2
return 0;
}
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
using namespace std;
class X
{
public:
X()
{
cout << "X ..." << endl;
}
~X()
{
cout << "~X ..." << endl;
}
void Fun()
{
cout << "Fun ..." << endl;
}
};
int main(void)
{
boost::weak_ptr<X> p;
{
boost::shared_ptr<X> p2(new X);
cout << p2.use_count() << endl;
p = p2;
cout << p2.use_count() << endl;
boost::shared_ptr<X> p3 = p.lock();
if (!p3)
cout << "object is destroyed" << endl;
else
p3->Fun();
}
boost::shared_ptr<X> p4 = p.lock();
if (!p4)
cout << "object is destroyed" << endl;
else
p4->Fun();
return 0;
}
scoped_array/shared_array
boost::scoped_array<X> xx(new X[3]);//数组
boost::shared_array<X> xx(new X[3]);//数组