例子:
执行结果如下:
ewuming/morgan> ./a.out
string2: 5 string2 address: 0x804b008
string2: hello
str1 is an smart pointer!!! : 0x804b008
!!!!!!! : 0
str1 content after reset: world!
auto_ptr的根本原理:
智能指针的关键技术:在于构造栈上对象的生命期控制堆上构造的对象的生命期.因为在智能指针的内部,存储着堆对象的指针,而且在构析函数中调用delete行为。
如果几个auto_ptr指向同一个对象,那么,退出的时候,每个auto_ptr都会执行delete操作。程序最终crash。
smart pointer is smart, however, man is most of important.
Other experience:
1,auto_ptr存储的指针应该为NULL或者指向动态分配的内存块。
2,auto_ptr存储的指针应该指向单一物件(是new出来的,而不是new[]出来的)。
3,两个auto_ptr对象不会同时指向同一块内存块。要明白2个auto_ptr对象赋值会发生什么。
4,千万不要把auto_ptr对象放在容器中。
5,当将auto_ptr作为函数参数时,最好声明为const auto_ptr<T>&(by const ref).当函数返回值可以简单的传值(by value).
Web links:
http://blog.csdn.net/cyblueboy83/archive/2007/09/20/1792463.aspx