歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++智能指針--auto_ptr指針

C++智能指針--auto_ptr指針

日期:2017/3/1 9:42:18   编辑:Linux編程

這裡先介紹auto_ptr的缺陷:

因為auto_ptr並不是完美無缺的,它的確很方便,但也有缺陷,在使用時要注意避免。首先,不要將auto_ptr對象作為STL容器的元素。C++標准明確禁止這樣做,否則可能會碰到不可預見的結果

auto_ptr的另一個缺陷是將數組作為auto_ptr的參數: auto_ptr<char> pstr (new char[12] ); //數組;為定義
然後釋放資源的時候不知道到底是利用delete pstr,還是 delete[] pstr;

然後收集了關於auto_ptr的幾種注意事項:
1、auto_ptr不能共享所有權。
2、auto_ptr不能指向數組
3、auto_ptr不能作為容器的成員。
4、不能通過賦值操作來初始化auto_ptr
std::auto_ptr<int> p(new int(42)); //OK
std::auto_ptr<int> p = new int(42); //ERROR
這是因為auto_ptr 的構造函數被定義為了explicit
5、不要把auto_ptr放入容器
這個指針已經被丟棄了!

C++ Primer Plus 第6版 中文版 清晰有書簽PDF+源代碼 http://www.linuxidc.com/Linux/2014-05/101227.htm

讀C++ Primer 之構造函數陷阱 http://www.linuxidc.com/Linux/2011-08/40176.htm

讀C++ Primer 之智能指針 http://www.linuxidc.com/Linux/2011-08/40177.htm

讀C++ Primer 之句柄類 http://www.linuxidc.com/Linux/2011-08/40175.htm

Copyright © Linux教程網 All Rights Reserved