【STL】-auto_ptr的用法

初始化:

1 #include<memory> //auto_ptr header
2 void f()
3 {
4   auto_ptr<classA> ptr(new classA);
5 }

拷贝:

1 //auto_ptr can't be initialized by = operator
2 auto_ptr<classA> ptr1(new classA); //OK
3 auto_ptr<classA> ptr2 = new classA; //NOK
4 ptr1 = auto_ptr<classA>(new int(42)); //OK
5 ptr1 = new int 42; //NOK

要点:

1. auto_ptr不可以指向array,因为auto_ptr用的是delete而不是delete []

2. auto_ptr不能作为容器的元素,因为不符合基本的拷贝后两个值要相等的要求,auto_ptr拷贝后,前者交出拥有权

3. const auto_ptr的指向不能有变化,但是其指向的值可以有变化。 p, q都是const auto_ptr, p = q不可以,但是*p = *q是可以的

posted on 2014-07-22 08:53  醉清风JM  阅读(207)  评论(0编辑  收藏  举报

导航