scoped_ptr,scoped_array

来源:互联网 发布:rtu是什么数据 编辑:程序博客网 时间:2024/06/06 03:52

----------------------------------------------------------------------------参考《boost程序库完全开发指南》作者罗剑锋---------------------------------------------------------------------------------------------

#include<boost\smart_ptr.hpp>#include<iostream>using namespace boost;int main() {/*scoped_ptr的构造函数接受一个类型为T*的指针p,创建出一个scoped_ptr对象p必须是一个new表达式分配的结果,或者是一个空指针scoped_ptr的生命周期结束时,析构函数~scoped_ptr会使用delete操作符自动销毁所保存的指针对象scoped_ptr不能拷贝构造,即scoped_ptr s2 = s1是错误的*///scoped_ptr用法一scoped_ptr<std::string> sp(new std::string("text"));std::cout << *sp << std::endl;std::cout << sp->size() << std::endl;//scoped_ptr用法二struct posix_file {posix_file(std::string filename) {std::cout << "open file " << filename << std::endl;}~posix_file() {std::cout << "close file" << std::endl;}};scoped_ptr<int> p(new int);if (p) {*p = 100;std::cout << *p << std::endl;}p.reset();               //reset()置空scoped_ptrassert(p == 0);          //p不持有任何指针if (!p) {std::cout << "scoped_ptr is null!" << std::endl;}scoped_ptr<posix_file> fp(new posix_file("wasda"));//在这里发生p和fp的删除return 0;}/*auto_ptr和scoped_ptr的区别:auto_ptr可以转移所有权,scoped_ptr管理的指针只有自己能访问,不能进行转移auto_ptr<int> ap(new int(10));           scoped_ptr<int> sp(ap);              //从auto_ptr获得原始指针assert(ap.get() == 0)                //原auto_ptr不再拥有指针ap.reset(new int(20));               //ap获得新指针auto_ptr<int> ap2;ap2 = ap;                            //ap2从ap获得原始指针,发生所有权转移assert(ap.get() == 0)                //ap不再拥有指针scoped_ptr<int> sp2;                 //另一个scoped_ptrsp2 = sp;                            //赋值操作,无法编译通过scoped_ptr和auto_ptr都可以从auto_ptr获得指针的所有权,但是无法从scoped_ptr获得指针,因为scoped_ptr管理的指针只允许自己访问*/
#include<iostream>#include<algorithm>#include<boost/smart_ptr.hpp>using namespace boost;int main() {int *arr = new int[100];scoped_array<int> sa(arr);std::fill_n(&sa[0], 100, 5);sa[10] = sa[20] + sa[30];              //scoped_array重载了[]运算符,所以可以像普通数组一样使用,但是不支持指针运算for (int i = 0; i < 100; i++) {std::cout << sa[i] << " ";}return 0;}



0 0
原创粉丝点击