代碼段(正常指針)普通指針VS自動指針(標準:: auto_ptr的)
int *pi = new int;
int i = 90;
pi = &i;
int k = *pi + 10;
cout<<k<<endl;
delete pi;
[Output: 100]
代碼段(自動指針)
案例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)
案例2:
std::auto_ptr<int> pi(new int);
int i = 90;
*pi = 90;
int k = *pi + 10;
cout<<k<<endl;
[Output: 100]
有人可以告訴爲什麼它沒有爲案例1工作?
情況1實際上應該編譯失敗(沒有操作符來執行'pi =&i;'),所以我看不到你如何調試這段代碼。 – visitor 2010-04-23 11:05:36
它沒有編譯失敗。 (我正在編譯與vc8) – AKN 2010-04-23 12:16:20
你似乎碰到過這個bug:http://connect.microsoft.com/VisualStudio/feedback/details/98871/ - 好吧,@visitor已經找到了一個。 – 2010-04-23 13:01:53