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
- scoped_ptr,scoped_array
- 关于scoped_ptr和scoped_array
- auto_ptr scoped_ptr scoped_array shared_ptr weak_ptr
- boost库学习之 scoped_ptr scoped_array
- boost 智能指针auto_ptr scoped_ptr shared_ptr scoped_array shared_array 总结
- c++智能指针:boost::scoped_ptr,boost::shared_ptr,boost::scoped_array
- scoped_array
- scoped_array
- 智能指针 boost(scoped_ptr,scoped_array,shared_ptr,shared_array) 和 std (auto_ptr)的比较 .
- 《我的泛型编程观》之boost.scoped_ptr、scoped_array源码分析
- C++学习之智能指针--auto_ptr、scoped_ptr、scoped_array、shared_ptr、shared_array、weak_ptr
- 【C++】智能指针的作用,模拟实现auto_ptr,scoped_ptr,shared_ptr,scoped_array,shared_array
- Boost库高效内存管理——smart_ptr库——scoped_ptr/scoped_array
- scoped_ptr
- scoped_ptr
- scoped_ptr
- scoped_ptr
- scoped_ptr
- C语言编写log文件以及printf函数实现原理
- Python中strip(),lstrip(), rstrip()使用方法
- 应用层常见的协议及对应的端口号
- Mac 上编译 ffmpeg 方法
- 手把手教你使用Git
- scoped_ptr,scoped_array
- java并发库之Executors常用的创建ExecutorService的几个方法说明
- 可执行程序的装载
- Hibernate 的三种查询方式:HQL、Criteria、Sql
- 相对路径与绝对路径
- 使用github进行多人开发
- 干货--Redis 30分钟快速入门
- C# 对WinForm应用程序的App.config的使用及加密
- GeoHash