您的位置:首页 > 其它

(十二)动态内存与智能指针

2014-06-24 15:29 239 查看
shared_ptr<T> p;

shared_ptr<int> p = make_shared<int>(42);//效率比下面的高
shared_ptr<int> p2(new int(42));//不推荐,为了避免智能指针与普通指针的混用,所以最后使用make_shared,这样在内存分配之后立刻与智能指针绑定到一起.


new 如果失败,会抛出异常

RAII 确保资源得以释放,除非线程意外被终止,否则会进行栈展开,释放栈对象.

HANDLE handle;//Created or opened
shared_ptr<HANDLE> hClose( &handle, []( HANDLE* h ){CloseHandle( h ); } );


unique_ptr 独占智能指针,不支持拷贝赋值等操作.除非这个unique_ptr将要被销毁,这种情况,编译器执行一种特殊的"拷贝"

unique_ptr<int> p1(new int(42));
unique_ptr<int> p2(p1);//error
unique_ptr<int> p3 = p1;/error

unique_ptr<int> clone(int p)
{
unique_ptr<int> ret(new int(p));
return ret; //ok
}


weak_ptr 等同于shared_ptr,但是不会增加使用技术,不会释放对象.

auto p = make_shared<int>(10);
weak_ptr<int>wp(p);

if(shared_ptr<int> np = wp.lock())
{
//使用np访问共享对象
}

不会影响对象的生存期,但是可以阻止用户访问一个不再存在的对象的企图,(不会影响吗?经测试,会影响,shared_ptr<int> np = wp.lock() 之后会增加使用计数)

动态数组:

2种方法,new type[num];allocator

new int[20]; 这样的并非是一个数组类型,不能使用begin或end,也不能使用范围for;

delete [] p;

智能指针管理动态数组

unique_ptr<int[] up(new int[10]);

当unique_ptr指向数组时,可以用下标访问元素

shared_ptr不支持管理动态数组,如果使用shared_ptr管理动态数组,需要提供自定义的删除器

shared_ptr<int> sp(new int[20],[](int *p){delete[] p;});

访问需要 sp.get() 获取内置指针,这样不方便.

allocator

把内存分配和对象构造分离开来

allocate 分配内存

construct 构造

destroy 析构

deallocate 释放内存 必须与allocate的指针,大小一样.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: