scoped_ptr有个特点是:所管理的对象的所有权不能被共享和转移,但是可以交换。
1.问题:如何做到不被共享和转移?
查看其源码,得知:私有了拷贝构造函数和赋值运算符重载函数
template<class T> class scoped_ptr // noncopyable
{
private:
T * px;
scoped_ptr(scoped_ptr const &);
scoped_ptr & operator=(scoped_ptr const &);
typedef scoped_ptr<T> this_type;
void operator==( scoped_ptr const& ) const;
void operator!=( scoped_ptr const& ) const;
...
}
2.演示所有权交换
#include <iostream>
#include <string>
#include <boost/scoped_ptr.hpp>
using namespace std;
class Masterpiece
{
private:
string name_;
public:
Masterpiece(string name) : name_(name)
{
cout << "Construct Masterpiece " <<"<< "<< name_ << " >>"<< endl;
}
~Masterpiece()
{
cout << "Destroyed Masterpiece " << "<< " << name_ << " >>" << endl;
}
};
int main()
{
cout << "=====Demo Begin=====" << endl;
{
boost::scoped_ptr<Masterpiece>masterpiece1(new Masterpiece("三国演义"));
boost::scoped_ptr<Masterpiece> masterpiece2(new Masterpiece("西游记"));
masterpiece1.swap(masterpiece2);
}
cout << "===== Demo End =====" << endl;
cin.get();
return 0;
}
说明:先构造的对象后析构,没有交换之前打印内容,对比交换之后的打印内容,即可验证
待续…
本文介绍了scoped_ptr的特点及其如何通过私有化拷贝构造函数和赋值运算符来避免对象所有权的共享与转移。此外,还通过一个示例演示了所有权交换的过程。
1231

被折叠的 条评论
为什么被折叠?



