boost smart_ptr -> scoped_ptr
2017-02-25 12:36
399 查看
scoped_ptr P78
C++98 的标准“自动指针”:std::auto_ptr#include <boost/smart_ptr.hpp> using namespace boost;
只能在本作用域内使用,不希望被转让。
a. 不支持比较操作
b. .swap()交换两个scoped_ptr保存的原始指针,高效操作。
c. 缺陷:不能用作容器的元素
scoped_prt<string> sp(new string("text")); cout<< *sp <<endl; cout<< sp->size() <<endl;
#include <iostream> #include <boost/assert.hpp> #include <boost/smart_ptr.hpp> using namespace std; using namespace boost; struct posix_file //一个示范性质的文件类 { posix_file(const char* file_name) //构造函数打开文件 { cout << "Open file:" << file_name << endl; } ~posix_file() { cout << "close file" << endl; } }; int main(int argc, char *argv[]) { scoped_ptr<int> p(new int); if(p) //在bool语境中测试指针是否有效 { *p = 100; cout << *p << endl; } p.reset(); //reset()置空scoped_ptr,仅仅是演示 assert(p == 0); //p不持有任何指针 if(!p) { cout << "scoped_ptr == null" << endl; } //文件类的scoped_ptr //将在离开任用域时自动析构,从而关闭文件释放资源 scoped_ptr<posix_file> fp(new posix_file("/tmp/a.txt")); return 0; }
相关文章推荐
- Boost源码剖析--<boost/smart_ptr/scoped_ptr.hpp>
- boost smart_prt 4-> shared_ptr
- boost :: scoped_ptr的和std ::的unique_ptr的区别 是之间的唯一不同boost::scoped_ptr<T>和std::unique_ptr<T>的事实std::uni
- boost.smart_ptr-智能指针scoped_array
- boost::scoped_ptr<CUser> apUser(new CUser);
- boost.smart_ptr-智能指针scoped_array
- 从零开始学C++之boost库(一):详解 boost 库智能指针(scoped_ptr<T> 、shared_ptr<T> 、weak_ptr<T> 源码分析)
- boost.smart_ptr-智能指针scoped_ptr
- [置顶] 从零开始学C++之boost库(一):详解 boost 库智能指针(scoped_ptr<T> 、shared_ptr<T> 、weak_ptr<T> 源码分析)
- 详解 boost 库智能指针(scoped_ptr<T> 、shared_ptr<T> 、weak_ptr<T> 源码分析)
- boost.smart_ptr-智能指针scoped_ptr
- boost.smart_ptr-智能指针scoped_ptr
- [置顶] 从零开始学C++之boost库(一):详解 boost 库智能指针(scoped_ptr<T> 、shared_ptr<T> 、weak_ptr<T> 源码分析)
- Boost.smart_ptr.scoped_ptr--1
- 详解 boost 库智能指针(scoped_ptr<T> 、shared_ptr<T> 、weak_ptr<T> 源码分析)
- boost.smart_ptr-智能指针scoped_ptr
- mongodb 中 scoped_ptr.hpp:99: T* boost::scoped_ptr<T>::operator->() const [with T = mongo::AtomicWord
- boost中类似于 shared_array<int> ptr(0) error
- boost___smart_ptr
- C/C++: std::auto_ptr 与 boost:: scoped_ptr 区别