auto_ptr & share_ptr & unique_ptr
2024-08-28 12:07:27
Using auto_ptr, you don’t need think about the memory deallocation, but there are also many arguments about it because of auto_ptr ownership translation.
void AutoPtrTest(void)
{
std::auto_ptr<int> p1 (new int());
//pass ownership
std::auto_ptr<int> p2 = p1;
std::cout << "p1 will raise exception:" << *p1 << std::endl;
std::cout << "p2 is ok: " << *p2 << std::endl;
}
In C++11, the auto_ptr is deprecated. The shared_ptr and unique_ptr are designed which have more security and comprehensive.
void AutoPtrTest(void)
{
std::auto_ptr<int> p1 (new int());
//pass ownership
std::auto_ptr<int> p2 = p1; //here has a warning in GCC
//std::cout << "p1 will raise exception:" << *p1 << std::endl;
std::cout << "p2 is ok: " << *p2 << std::endl; std::shared_ptr<int> s1 (new int());
std::shared_ptr<int> s2 = s1; //share it. point to same address
std::cout << "s1 is ok:" << *s1 << std::endl;
std::cout << "s2 is ok: " << *s2 << std::endl; std::unique_ptr<int> u1 (new int());
// std::unique_ptr<int> u2 = u1; //cannot be compiled
std::cout << "u1 is ok:" << *u1 << std::endl;
// std::cout << "s2 is ok: " << *s2 << std::endl;
}
In conclusion, auto_ptr could be replaced by shared_ptr or unique_ptr depending upon situation.
最新文章
- Prince2七大原则(4)
- NOSCRIPT标签的用处
- leetcode 168
- 蓝牙版本V4.2特征讲解说明
- 转--CSS选择器详解(一)常用选择器
- 多功能节点连线绘图控件Nevron Diagram for .NET使用方法及下载地址
- UVaLive6039 Uva1668 Let&#39;s Go Green
- IOS开发-UIView之动画效果的实现方法(合集)
- Java加密解密与数字证书的操作
- is,as,sizeof,typeof,GetType
- hdu_1403_Longest Common Substring(后缀数组的应用)
- cocopods安装与使用
- BZOJ 3198: [Sdoi2013]spring [容斥原理 哈希表]
- Uva - 514 - Rails
- android异步任务asyntask详解
- Windows 7无声音的解决方案
- npm cnpm +nodejs
- camera-arm-RPI
- Html5——视频标签使用
- Linux的用户