智能指针模拟实现: http://blog.youkuaiyun.com/snow_5288/article/details/53262810
在以上文章中,我们对库里的某些智能指针进行了模拟实现,今天就来学习解剖一下库里的智能指针的实现和使用。
一、总括
对于编译器来说,智能指针实际上是一个栈对象,并非指针类型,在栈对象生命期即将结束时,智能指针通过析构函数释放有它管理的堆内存。
接口:
- - 所有智能指针都重载了“operator->”操作符,直接返回对象的引用,用来操作对象。
- - 访问智能指针原来的方法则使用“.”操作符。
- - 访问智能指针包含的裸指针则可以用 get() 函数。
- - 由于智能指针是一个对象,所以if (my_smart_object)永远为真,要判断智能指针的裸指针是否为空,需要这样判断:if (my_smart_object.get()).
- - 智能指针包含了 reset() 方法,如果不传递参数(或者传递 NULL),则智能指针会释放当前管理的内存。如果传递一个对象,则智能指针会释放当前对象,来管理新传入的对象。
下面编写一个测试类来辅助分析:
class Simple
{
public:
Simple(int num = 0)
:_num(num)
{
cout << "Simple:" << _num << endl;
}
~Simple()
{
cout << "~Simple:" << _num << endl;
}
void PrintSomething()
{
cout << "PrintSomething:" << _info.c_str() << endl;
}
int _num;
static string _info;
};
string Simple::_info = "";
二、std::auto_ptr
std::auto_ptr 属于 STL,在 namespace std 中,包含头文件 #include 便可以使用。std::auto_ptr 能够方便的管理单个堆内存对象。
auto_ptr的接口:
测试用例:
void TestAutoPtr1()
{
auto_ptr<Simple> ap1(new Simple(1));//创建对象,输出:Simple:1
if (ap1.get())//判断智能指针是否为空
{
ap1->PrintSomething();// 使用 operator-> 调用智能指针对象中的函数
ap1.get()->_info = "hello";// 使用 get() 返回裸指针,然后给内部对象赋值
ap1->PrintSomething();// 再次打印,表明上述赋值成功
(*ap1)._info += " world";// 使用 operator* 返回智能指针内部对象,然后用“.”调用
ap1->PrintSomething();// 再次打印,表明上述赋值成功
}
// ap1栈对象即将结束生命期,析构堆对象 Simple(1)
}
运行结果:
但是,好景不长:
void TestAutoPtr2()
{
auto_ptr<Simple> ap1(new Simple(2));//创建对象,输出:Simple:2
if (ap1.get())
{
std::auto_ptr<Simple> ap2;// 创建一个新的 ap2 对象
ap2 = ap1; // 复制旧的 ap1 给 ap2
ap2->PrintSomething();// 输出信息,复制成功
ap1->PrintSomething();// 崩溃,因为ap1已经失去了内存的管理权
}
}
最终如上代码导致崩溃,如上代码时绝对符合 C++ 编程思想的,居然崩溃了,跟进 std::auto_ptr 的源码后,我们看到,罪魁祸首是“ap2 = ap1”,这行代码,ap2 完全夺取了 ap1 的内存管理所有权,导致 ap1 悬空,最后使用时导致崩溃。
所以,使用 std::auto_ptr 时,绝对不能使用“operator=”操作符。作为一个库,不允许用户使用,确没有明确拒绝,多少会觉得有点出乎预料。
接着往下看:
void TestAutoPtr3()
{
auto_ptr<Simple> ap1(new Simple(3));//创建对象,输出:Simple:3
if (ap1.get())
{
ap1.release();//std::auto_ptr 的 release() 函数只是让出内存所有权
}
}
运行结果:
看到什么异常了吗?我们创建出来的对象没有被析构,没有输出 “~Simple: 3”,导致内存泄露。当我们不想让ap1继续生存下去,我们调用 release() 函数释放内存,结果却导致内存泄露(在内存受限系统中,如果ap1占用太多内存,我们会考虑在使用完成后,立刻归还,而不是等到 ap1 结束生命期后才归还)。
正确的代码:
void TestAutoPtr3()
{
std::auto_ptr<Simple> ap1(new Simple(3));
if (ap1.get())
{
Simple* temp = ap1.release();
delete temp;
}
或
void TestAutoPtr3()
{
std::auto_ptr<Simple> ap1(new Simple(3));
if (ap1.get())
{
ap1.reset(); // 释放 ap1 内部管理的内存
}
}
auto_ptr总结:
std::auto_ptr 可用来管理单个对象的对内存,但是,请注意如下几点:
(1) 尽量不要使用“operator=”。如果使用了,请不要再使用先前对象。
(2) 记住 release() 函数不会释放对象,仅仅归还所有权。
(3) std::auto_ptr 最好不要当成参数传递(读者可以自行写代码确定为什么不能)。
(4) 由于 std::auto_ptr 的“operator=”问题,有其管理的对象不能放入 std::vector 等容器中。
(5) ……
由于 std::auto_ptr 引发了诸多问题,一些设计并不是非常符合 C++ 编程思想,所以引发了下面 boost 的智能指针,boost 智能指针可以解决如上问题。
三、boost::scoped_ptr(独享所有权)
boost::scoped_ptr 属于 boost 库,定义在 namespace boost 中,包含头文件 #include<boost/smart_ptr.hpp>
便可以使用。boost::scoped_ptr 跟 std::auto_ptr 一样,可以方便的管理单个堆内存对象,特别的是,boost::scoped_ptr 独享所有权,避免了 std::auto_ptr 恼人的几个问题。
应用举例:
void TestScopedPtr()
{
boost::scoped_ptr<Simple> ap1(new Simple(1));
if (ap1.get())
{
ap1->PrintSomething();
ap1.get()->_info = "hello";
ap1->PrintSomething();
(*ap1)._info+= " world";
ap1->PrintSomething();
ap1.release(); // 编译 error: scoped_ptr 没有 release 函数
std::auto_ptr<Simple> ap2;
ap1 = ap1; // 编译 error: scoped_ptr 没有重载 operator=,不会导致所有权转移
}
}
首先,我们可以看到,boost::scoped_ptr 也可以像 auto_ptr 一样正常使用。但其没有 release() 函数,不会导致先前的内存泄露问题。
其次,由于 boost::scoped_ptr 是独享所有权的,所以明确拒绝用户写“ap2 = ap1”之类的语句,可以缓解 std::auto_ptr 几个恼人的问题。
由于 boost::scoped_ptr 独享所有权,当我们真正需要复制智能指针时,需求便满足不了了,如此我们再引入一个智能指针,专门用于处理复制,参数传递的情况,这便是如下的 boost::shared_ptr。
四、boost::shared_ptr
boost::shared_ptr 属于 boost 库,定义在 namespace boost 中,包含头文件 #include
void TestSharedPtr(boost::shared_ptr<Simple> memory)
{ // 注意:无需使用 reference (或 const reference)
memory->PrintSomething();
cout << "TestSharedPtr UseCount: " << memory.use_count()<<endl;
}
void TestSharedPtr2()
{
boost::shared_ptr<Simple> ap(new Simple(1));
if (ap.get())
{
ap->PrintSomething();
ap.get()->_info = "hello";
ap->PrintSomething();
(*ap)._info += " world";
ap->PrintSomething();
}
cout << "TestSharedPtr2 UseCount: " << ap.use_count() << endl;
TestSharedPtr(ap);
std::cout << "TestSharedPtr2 UseCount: " << ap.use_count() << endl;
//ap.release();// 编译 error: 同样,shared_ptr 也没有 release 函数
}
执行结果:
Simple: 1
PrintSomething:
PrintSomething: hello
PrintSomething: hello world
TestSharedPtr2 UseCount: 1
PrintSomething: hello world
TestSharedPtr UseCount: 2
TestSharedPtr2 UseCount: 1
~Simple: 1
总结:boost::shared_ptr 也可以很方便的使用。并且没有 release() 函数。关键的一点,boost::shared_ptr 内部维护了一个引用计数,由此可以支持复制、参数传递等。boost::shared_ptr 提供了一个函数 use_count() ,此函数返回 boost::shared_ptr 内部的引用计数。查看执行结果,我们可以看到在 TestSharedPtr2 函数中,引用计数为 1,传递参数后(此处进行了一次复制),在函数TestSharedPtr 内部,引用计数为2,在 TestSharedPtr 返回后,引用计数又降低为 1。当我们需要使用一个共享对象的时候,boost::shared_ptr 是再好不过的了。
五、boost::scoped_array
boost::scoped_array 属于 boost 库,定义在 namespace boost 中,包含头文件 #include
void TestScopedArray()
{
boost::scoped_array<Simple> ap(new Simple[2]); // 使用内存数组来初始化
if (ap.get()) {
ap[0].PrintSomething();
ap.get()[0]._info= "Addition";
ap[0].PrintSomething();
(*ap)[0]._info+= " other"; // 编译 error,scoped_ptr 没有重载 operator*
ap[0].release(); // 同上,没有 release 函数
boost::scoped_array<Simple> ap2;
ap2= ap; // 编译 error,同上,没有重载 operator=
}
}
boost::scoped_array 的使用跟 boost::scoped_ptr 差不多,不支持复制,并且初始化的时候需要使用动态数组。另外,boost::scoped_array 没有重载“operator*”,其实这并无大碍,一般情况下,我们使用 get() 函数更明确些。
下面肯定应该讲 boost::shared_array 了,一个用引用计数解决复制、参数传递的智能指针类。
六、boost::shared_array
boost::shared_array 属于 boost 库,定义在 namespace boost 中,包含头文件 #include
void TestSharedArray(boost::shared_array<Simple> memory)
{ // 注意:无需使用 reference (或 const reference)
cout<<"TestSharedArray UseCount: " << memory.use_count()<<endl;
}
void TestSharedArray2()
{
boost::shared_array<Simple> ap(new Simple[2]);
if (ap.get()) {
ap[0].PrintSomething();
ap.get()[0]._info= "Addition 00";
ap[0].PrintSomething();
pa[1].PrintSomething();
ap.get()[1]._info = "Addition 11";
ap[1].PrintSomething();
//(*ap)[0]._info+= " other"; // 编译 error,scoped_ptr 没有重载 operator*
}
std::cout << "TestSharedArray2 UseCount: " << ap.use_count() << std::endl;
TestSharedArray(ap);
std::cout << "TestSharedArray2 UseCount: " << ap.use_count() << std::endl;
}
运行结果:
Simple: 0
Simple: 0
PrintSomething:
PrintSomething: Addition 00
PrintSomething:
PrintSomething: Addition 11
TestSharedArray2 UseCount: 1
TestSharedArray UseCount: 2
TestSharedArray2 UseCount: 1
~Simple: 0
~Simple: 0
七、boost::weak_ptr
boost::weak_ptr 属于 boost 库,定义在 namespace boost 中,包含头文件 #include
void TestWeakPtr()
{
boost::weak_ptr<Simple> my_memory_weak;
boost::shared_ptr<Simple> my_memory(new Simple(1));
std::cout << "TestWeakPtr boost::shared_ptr UseCount: " << my_memory.use_count() << std::endl;
my_memory_weak = my_memory;
std::cout << "TestWeakPtr boost::shared_ptr UseCount: " << my_memory.use_count() << std::endl;
}
执行结果:
Simple: 1
TestWeakPtr boost::shared_ptr UseCount: 1
TestWeakPtr boost::shared_ptr UseCount: 1
~Simple: 1
我们看到,尽管被赋值了,内部的引用计数并没有什么变化,当然,读者也可以试试传递参数等其他情况。
现在要说的问题是,boost::weak_ptr 到底有什么作用呢?从上面那个例子看来,似乎没有任何作用,其实 boost::weak_ptr 主要用在软件架构设计中,可以在基类(此处的基类并非抽象基类,而是指继承于抽象基类的虚基类)中定义一个 boost::weak_ptr,用于指向子类的 boost::shared_ptr,这样基类仅仅观察自己的 boost::weak_ptr 是否为空就知道子类有没对自己赋值了,而不用影响子类 boost::shared_ptr 的引用计数,用以降低复杂度,更好的管理对象。
八、boost::intrusive_ptr
boost::intrusive_ptr属于 boost 库,定义在 namespace boost 中,包含头文件 #include
九、总结
1、在可以使用 boost 库的场合下,拒绝使用 std::auto_ptr,因为其不仅不符合 C++ 编程思想,而且极容易出错。
2、在确定对象无需共享的情况下,使用 boost::scoped_ptr(当然动态数组使用 boost::scoped_array)。
3、在对象需要共享的情况下,使用 boost::shared_ptr(当然动态数组使用 boost::shared_array)。
4、在需要访问 boost::shared_ptr 对象,而又不想改变其引用计数的情况下,使用 boost::weak_ptr,一般常用于软件框架设计中。
5、最后一点,也是要求最苛刻一点:在你的代码中,不要出现 delete 关键字(或 C 语言的 free 函数),因为可以用智能指针去管理。
参考文章:http://blog.youkuaiyun.com/xt_xiaotian/article/details/5714477