from http://blog.csdn.net/stevenliyong/article/details/3728204 2009.01 C++使用对象来管理动态分配资源 1. 引入 代码本身没有问题,但这个存在隐患,程序员必须很小心的处理delete 才不至于出现内存泄露. 为了确保 createInvestment 返回的资源总能被释放,
但是存在问题,auto_ptr 只允许一个auto_prt对象指向Investment资源 正因为如此 auto_ptrs 的STL容器是不被允许的。
tr1::shared_ptr能持续跟踪有多少 objects(对象)指向一个特定的资源, std::tr1::shared_ptr<Investment> // pInv1 points to the std::tr1::shared_ptr<Investment> // both pInv1 = pInv2; // ditto — nothing has tr1::shared_ptrs 能被用于 STL容器以及其它和 auto_ptr 的非正统的拷贝行为不相容的环境中。
std::auto_ptr<std::string> // bad idea! the wrong std::tr1::shared_ptr<int> spi(new int[1024]); // same problem 这样的使用会导致auto_ptr或tr1::shared_ptr只删除一个string和int对象,而不是对象的数组引起内存泄露 C++ 甚至在 TR1 都没有可用于动态分配数组的类似auto_ptr或tr1::shared_ptr这样的东西。 如果非要对动态分配数组资源使用对象管理,可以用boost库中的 boost::scoped_array 和 boost::shared_array 函数. |
|
来自: 心不留意外尘 > 《ccpp for hardware》