先來看一段簡單的代碼:
#include <iostream>
#include <memory>
using namespace std;
void test_smartpointer(shared_ptr<int> sp)
{
(*sp)++;
}
void test_pointer(int *p)
{
(*p)++;
}
int main()
{
int n1 = 5, n2 = 5;
shared_ptr<int> sp (new int(n1))
test_smartpointer(sp);
n1=*sp;
test_pointer(&n2);
cout << "n1 = " << n1 << " n2 = " << n2 << endl;
return 0;
}
輸出結果爲:n1 = 6 n2 = 6
智能指針的使用稍顯麻煩,出於我們之前使用指針的習慣,文中的shared_ptr<int> sp(new int(n1))可否換成shared_ptr<int> sp(&n1)呢?
如此一來不就省去了後面的n1=*sp嗎?
答案是不能。因爲shared_ptr對自己管理的內存會自動釋放,而在本段代碼中,n1是棧上的對象,會自動被清理。那麼問題來了,n1可能會被清理兩次。
我在使用gcc4.6.3發現此問題後,又分別使用VS和mingw做了驗證。
奇怪的是在vs2013社區版中不會報錯,mingw也沒報錯。
後面我又找了一些對C++11/14完全支持的在線編譯器,結果在直接傳入棧上對象的地址後果然報錯了。
所以在使用微軟的編譯器或mingw的時候需謹慎。遇到有疑惑的代碼及時使用gcc/clang,或者在線編譯器驗證。
除了上面我用的那個之外,iso C++的網站上也提供了更多在線編譯器。