假設有一個函數:
int priority();
void processWidget(std::share_ptr<Widget> pw, int priority1);
調用的時候可能會這麼寫:
processWidget(std::share_ptr<Widget>{ new Widget }, priority());
在調用processWidget之前,編譯器必須創建代碼,做以下三件事:
1.調用priority()
2.執行“new Widget”
3.調用std::shared_ptr構造函數
但是c++編譯器可能會對這三件事的順序隱藏地做出調整,最終的順序可能是
2->1->3
這樣就有一個問題,如果priority()函數出了異常,那麼將會導致new Widget執行了,但沒有託管給shared_ptr,這樣就會有資源泄漏。
避免這個問題很簡單,使用分離語句:
std::shared_ptr<Widget> pw{ new Widget };
processWidget(pw, priority());
因爲編譯器對於“跨語句的各項操作”沒有重新排列的自由,只有在語句內它才擁有那個自由度。
結論:
以獨立語句將newed對象託管給只能指針。如果不這樣做,一旦出現異常,就有可能導致難以察覺的資源泄漏。