应该避免使用临时的shared_ptr对象,对此,boost上的说明是:假设有下面的代码,ok函数是正确的做法,而bad函数有可能会导致内存泄露,因为f函数参数的执行顺序可能是先new int(2),再执行g(),然后再执行shared_ptr<int>(),假设在g()方法中产生了异常,将不会再执行shared_ptr<int>(),new int(2)的内存泄露。 View...
shared_ptr(std::auto_ptr < Y > & r),从一个auto_ptr获得指针的管理权,引用计数置为1,同时auto_ptr失去指针的管理权。 “=” 赋值运算符,对于对象shared_ptr和auto_ptr,结果同构造函数。 当然,还有特殊的shared_ptr(Y * p,D d),第二个参数指定了析构时的一些特性,之后再做介绍。 reset() 对于不...
共享数组对应的类型是boost::shared_array,它的定义在boost/shared_array.hpp里。 #include <boost/shared_array.hpp> #include <iostream> int main() { boost::shared_array<int> i1(new int[2]); boost::shared_array<int> i2(i1); i1[0] = 1; std::cout << i2[0] << std::endl; } ...
scoped_array 轻巧方便,没有给程序增加额外负担,但是 scoped_array 功能有限,不能动态增长,也没有迭代器支持,不能搭配 STL 算法,仅有一个纯粹的“裸”数组接口。在需要动态数组的情况下我们应该使用 std::vector 。例如:boost::shared_ptr 主要特点 boost.smart_ptr 库中最有价值,最重要的组成部分。支持...
(); cout << p3.use_count() << endl; // 2 if(!p3) { cout << "objec is destoryed" << endl; } else { p3->Fun(); } } boost::shared_ptr<X> p4 = p.lock(); if(!p4) { cout << "objec is destoryed" << endl; } else { p4->Fun(); } boost::scoped_array<X> xx(...
和本章中所有的智能指针一样,boost::shared_array 也同样提供了 get() 和 reset() 方法。另外还重载了 operator bool()。 03、弱指针 >>>到目前为止介绍的各种智能指针都能在不同的场合下独立使用。相反,弱指针只有在配合共享指针一起使用时才有意义。弱指针 boost::weak_ptr 的定义在 boost/weak_ptr.hpp...
shared_ptr pointing to it is destroyed or reset. 先来看例程: 代码语言:cpp 代码运行次数:0 运行 AI代码解释 #include<boost/shared_ptr.hpp>#include<iostream>usingnamespacestd;classX{public:X(){cout<<"X ..."<<endl;}~X(){cout<<"~X ..."<<endl;}};intmain(void){cout<<"Entering main...
boost::shared_array,共享数组的行为类似于共享指针。 关键不同在于共享数组在析构时,默认使用 delete[] 操作符来释放所含的对象。 因为这个操作符只能用于数组对象,共享数组必须通过动态分配的数组的地址来初始化。 弱指针: boost::weak_ptr,弱指针只有在配合共享指针一起使用时才有意义。一个强引用当被引用的对...
5.scoped_array/shared_array 6.PIMPL技法 1.boost智能指针 智能指针是利用RAII(Resource Acquisition Is Initialization:资源获取即初始化)来管理资源 在构造函数中对资源初始化,在析构函数中对资源释放 智能指针的本质思想是: ...
包括:std::auto_ptr、boost::scoped_ptr、boost::shared_ptr、boost::scoped_array、boost::shared_array、boost::weak_ptr、boost:: intrusive_ptr。你可能会想,如此多的智能指针就为了解决new、delete匹配问题,真的有必要吗?看完这篇文章后,我想你心里自然会有答案。