-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautoptr2.cpp
More file actions
50 lines (43 loc) · 1012 Bytes
/
autoptr2.cpp
File metadata and controls
50 lines (43 loc) · 1012 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <cstdlib>
#include <memory>
#include <iostream>
using std::auto_ptr;
using std::ostream;
using std::cout;
using std::endl;
/* define output operator for auto_ptr
* print object value or NULL
*/
template <typename T>
ostream& operator<< (ostream& strm, const auto_ptr<T>& p)
{
// does p own an object ?
if(p.get() == NULL){
strm<<"NULL";
}
else{
strm<< *p;
}
return strm;
}
int main(int argc, char *argv[])
{
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; 运行时错误,指针r未定义,无法使用
*p = -77;
cout<<"after assigning values:"<<endl;
cout<<"p:"<<p<<endl;
cout<<"q:"<<q<<endl;
cout<<"r:"<<r<<endl;
//q=p; const修饰的auto_ptr无法移交拥有权
//r = p;
system("PAUSE");
return EXIT_SUCCESS;
}