Normal pointer vs Auto pointer (std::auto_ptr)

Posted by AKN on Stack Overflow See other posts from Stack Overflow or by AKN
Published on 2010-04-23T06:25:17Z Indexed on 2010/04/23 6:33 UTC
Read the original article Hit count: 268

Filed under:
|
|

Code snippet (normal pointer)

int *pi = new int;
int i = 90;
pi = &i;
int k = *pi + 10;
cout<<k<<endl; 
delete pi;

[Output: 100]

Code snippet (auto pointer)

Case 1:

std::auto_ptr<int> pi(new int);
int i = 90;
pi = &i;
int k = *pi + 10; //Throws unhandled exception error at this point while debugging.
cout<<k<<endl;
//delete pi; (It deletes by itself when goes out of scope. So explicit 'delete' call not required)

Case 2:

std::auto_ptr<int> pi(new int);
int i = 90;
*pi = 90;
int k = *pi + 10;
cout<<k<<endl;

[Output: 100]

Can someone please tell why it failed to work for case 1?

© Stack Overflow or respective owner

Related posts about c++

Related posts about pointers