auto_ptr使用入门与注意事项:
1、auto_ptr不能共享所有权。
An auto_ptr must not refer to an object that is owned by another auto_ptr (or other object).
下面的程序说明了所有权的问题:
//util/autoptr1.cpp
#include <iostream>
#include <memory>
using namespace std;
/* define output operator for auto_ptr
* - print object value or NULL
*/
template <class T>
ostream& operator<< (ostream& strm, const auto_ptr<T>& p)
{
//does p own an object ?
if (p.get() == NULL) {
strm << "NULL"; //NO: print NULL
}
else {
strm << *p; //YES: print the object
}
return strm;
}
int main()
{
auto_ptr<int> p(new int(42));
auto_ptr<int> q;
cout << "after initialization:" << endl;
cout << " p: " << p << endl;
cout << " q: " << q << endl;
q = p;
cout << "after assigning auto pointers:" << endl;
cout << " p: " << p << endl;
cout << " q: " << q << endl;
*q += 13; //change value of the object q owns
p = q;
cout << "after change and reassignment:" << endl;
cout << " p: " << p << endl;
cout << " q: " << q << endl;
}
The output of the program is as follows:
after initialization:
p: 42
q: NULL
after assigning auto pointers:
p: NULL
q: 42
after change and reassignment:
p: 55
q: NULL
2、auto_ptr不能指向数组
3、auto_ptr不能作为容器的成员。
4、不能通过赋值操作来初始化auto_ptr
std::auto_ptr<int> p(new int(42)); //OK
std::auto_ptr<int> p = new int(42); //ERROR
这是因为auto_ptr 的构造函数被定义为了explicit
5、下面的程序说明了 const auto_ptr的行为:
const auto_ptr与 type * const ptr;相似
//util/autoptr2.cpp
#include <iostream>
#include <memory>
using namespace std;
/* define output operator for auto_ptr
* - print object value or NULL
*/
template <class T>
ostream& operator<< (ostream& strm, const auto_ptr<T>& p)
{
//does p own an object ?
if (p.get() == NULL) {
strm << "NULL"; //NO: print NULL
}
else {
strm << *p; //YES: print the object
}
return strm;
}
int main()
{
const auto_ptr<int> p(new int(42));
const auto_ptr<int> q(new int(0));
const auto_ptr<int> r;
cout << "after initialization:" << endl;
cout << " p: " << p << endl;
cout << " q: " << q << endl;
cout << " r: " << r << endl;
*q = *p;
// *r = *p; //ERROR: undefined behavior
*p = -77;
cout << "after assigning values:" << endl;
cout << " p: " << p << endl;
cout << " q: " << q << endl;
cout << " r: " << r << endl;
// q = p; //ERROR at compile time
// r = p; //ERROR at compile time
}
Here, the output of the program is as follows:
after initialization:
p: 42
q: 0
r: NULL
after assigning values:
p: -77
q: 42
r: NULL