[内存管理]智能指针之shared_array
来源:互联网 发布:为什么c语言是黑窗口 编辑:程序博客网 时间:2024/05/16 05:04
shared_array类似shared_ptr,它包装了new[]操作符在堆上分配的动态数组,同样使用引用计数机制为动态数组提供了一个代理,可以在程序的生命同期里长期存在,直到没有任何引用后才释放内存。
类摘要:
template<class T> class shared_array{public: explicit shared_array(T *p = 0); template<class D> shared_array(T *p,D d); ~shared_array(); shared_array(shared_array const & r); shared_array &operator=(shared_array const &r); void reset(T *p = 0); template<class D> void reset(T *p, D d); T & operator[](std::ptrdiff_t i) const() const; T *get() const; bool unique() const; long use_count() const; void swap(shared_array<T> & b);};
shared_array与shared_ptr的区别如下:
1:构造函数接受的指针p必须是new[]的结果,而不能是new表达式。
2:提供operator[]操作符重载,可以像普通数组一样用下标访问元素。
3:没有*、->操作符重载,因为shared_array持有的不是一个普通指针。
4:析构函数使用delete[]释放资源,而不是delete。
使用示例:
#include <iostream>#include <boost/smart_ptr.hpp>using namespace boost;using namespace std;int main(){ //shared_array<int> sp(new int[100]); //a dynamic array int *p = new int[100]; //shared_array agent dynamic array shared_array<int> sa(p); //shared array,add reference count shared_array<int> sa2 = sa; sa[0] = 10; assert(sa2[0] == 10); cout << "use count:" << sa.use_count() << endl; cout << "No Problem..." << endl; //out of scope,remove dynamic array automatically}
运行结果:
use count:2
No Problem...
shared_array是shared_ptr和scoped_array的结合体,既具有shared_ptr的优点,也有scoped_array的缺点。
在使用shared_array重载的operator[]要注意,shared_array不提供数组索引的范围检查,如果超过了动态数组大小的索引或者是负数索引将引发未定义行为。
shared_array能力有限,大多情况下可以用shared_ptr<std::vector>或者std::vector<shared_ptr>代替。
这两个方案具有更高的灵活性和更好的安全性,所付出的代价几乎可以忽略不计。
- [内存管理]智能指针之shared_array
- [内存管理]智能指针之shared_array
- 智能指针 shared_array
- C++智能指针 shared_array
- C++智能指针shared_array
- 内存管理-智能指针
- 智能指针Boost.smart_ptr学习5--shared_array
- C++学习之智能指针--auto_ptr、scoped_ptr、scoped_array、shared_ptr、shared_array、weak_ptr
- c++之智能指针(二)之直接管理内存
- 内存管理与智能指针
- Boost 内存管理----智能指针
- C++内存管理神器之模板化的智能指针
- Boost练习3——内存管理之智能指针
- 内存管理之常用智能指针的用法和注意事项
- 内存管理之智能指针一:stl中的auto_ptr智能指针
- boost 智能指针auto_ptr scoped_ptr shared_ptr scoped_array shared_array 总结
- 动态内存之智能指针
- webkit内存管理1:智能指针
- 数的长度
- Linux 初始 RAM 磁盘(initrd)概述
- Windows Socket 1.1库函数查询索引
- C# 释放内存
- 例5:通过连接池获得连接
- [内存管理]智能指针之shared_array
- 大规模并发,企业级应用讨论
- Android使用NDK开发项目时的一些问题
- Linux I2C核心、总线与设备驱动
- 关于换工作_写在第四份工作伊始之时
- 例6:总结数据库连接的各种方式
- cs中response write后网页布局变了
- ortp库使用入门
- 持续集成工具hudson与maven2的结合