C++ 智能指针模板类(廿六)--自动内存管理
来源:互联网 发布:网络学术信息检索行为 编辑:程序博客网 时间:2024/05/22 16:07
#include <memory.h>using namespace std;class Done { string myS;public: Done(const string &s):myS(s){ }; void Doit(){ cout << myS << endl; }; };int main(int argc, const char * argv[]) { /** * 三种智能指针语法 * 对应头文件 memory.h * new double 返回指针指向新分配内存块(形参) * 删除了 delete * new[] 不能使用 auto_ptr和shared_ptr * new、new[] unique_ptr 都可以处理 */ //1、auto_ptr 如果两个智能指针相互赋值,可能崩溃,应该用深复制 auto_ptr<double> ap_d(new double(20.1f)); double t = *ap_d; cout << "double =" << t << endl; auto_ptr<string> ap_s(new string("dsfs")); auto_ptr<string> ap_s2(new string("dsfs2")); string s(*ap_s); cout << "string =" << s << endl; ap_s2 = ap_s; //不警告 //2、unique_ptr 如果两个智能指针相互赋值,首先编译错误 unique_ptr<double> up_d(new double(30)); unique_ptr<string> up_s(new string("unique_ptr")); unique_ptr<string> up_s2(new string("unique_ptr2")); //up_s2 = up_s; 语法警告了 up_s2 = move(up_s); //3、shared_ptr 适合多个对象指向同一指针 shared_ptr<double> sp_d(new double(40.2f)); shared_ptr<string> sp_s(new string("shared_ptr")); shared_ptr<string> sp_s2(new string("shared_ptr2")); sp_s2 = sp_s; //例子 { auto_ptr<Done> ap_D(new Done("123456")); ap_D->Doit(); } { unique_ptr<Done> up_D(new Done("asdfg")); up_D->Doit(); } { shared_ptr<Done> sp_D(new Done("nbvcx")); sp_D->Doit(); } return 0;}
0 0
- C++ 智能指针模板类(廿六)--自动内存管理
- 【C++】动态内存管理和智能指针
- 内存管理-智能指针
- C++内存管理神器之模板化的智能指针
- 智能指针的模板,用来管理动态分配的内存
- 【C++】动态内存管理(四)智能指针(std)
- 内存管理与智能指针
- Boost 内存管理----智能指针
- 【C++】智能指针类和OpenCV的Ptr模板类
- [内存管理]智能指针之shared_array
- webkit内存管理1:智能指针
- [内存管理]智能指针之shared_array
- c++智能指针与内存管理
- c++内存管理和智能指针
- OSG内存管理——智能指针
- 谈C++内存管理与智能指针
- 动态内存管理与智能指针
- auto_ptr模板类 (智能指针)
- 《利用Python进行数据分析》--1--Windows环境下安装EPDFree和pandas
- P问题、NP问题以及NP难问题的相关信息查找结果
- debugger模式中查看request中的键值对
- CSDN系统升级公告!
- Serializable encounteredClassNotFoundException
- C++ 智能指针模板类(廿六)--自动内存管理
- windows和linux平台下java短信猫的配置
- eclipse配置JDK和设置编译版本的几种方法
- python时间处理
- 使用Xdoc,在jsp中进行各种文件转换
- mysql cast的错误用法
- PCH文件定义的 宏 不识别 implicit declaration of function “xxxx” is invalid in C99
- leetcode--Count Primes
- 用Pig实现sougou需求分析 (差作业里的那一小段)