当前位置: 首页 > news >正文

C++(4)C++内存管理和命名空间

内存管理

new/delete

C语言  malloc  free完成对堆内存的申请和释放。

C++  new  delete 类

new:动态申请存储空间的运算符,返回值为申请空间的对应数据类型的地址

int *p = new int(10);  申请了一个初始值为10的整型数据

int *p = new int[10];   申请了能存放10个整型数据元素的数组,其首地址为arr

单变量空间

#include <iostream>
#include <stdlib.h>
using namespace std;//malloc free  # include <stdlib.h>  库函数
//new delete key work 关键字int main()
{//Cint *p = (int*)malloc(sizeof(int));int *p = static_cast<int*>(malloc(sizeof(int)));//C++  单变量空间int *p = new int(200);//*p = 200;cout<<*p<<endl;string *ps = new string("aaa");//*ps = "china";cout<<*ps<<endl;struct Stu{int age;string name;};Stu *pStu = new Stu{10, "bob"};cout<<pStu->age<<endl;cout<<pStu->name<<endl;return 0;
}

多变量空间  数组

#include <iostream>
#include <string.h>  // #include <cstring>
#include <stdlib.h>
using namespace std;int main()
{char* p = new char[4];const char* source = "aa";strcpy_s(p, 4, source);cout << "p: " << p << endl;int *pi = new int[5]{0};memset(pi, 0, sizeof(int[5]));for(int i = 0; i < 5; i++){cout<<pi[i]<<endl;}char **ppc = new char*[5]{NULL};ppc[0] = new char[10];strcpy(ppc[0], "china");ppc[1] = "automan";ppc[2] = "greatwall";while(*ppc){cout<<*ppc++<<endl;}return 0;
}

一维、多维

#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;int main()
{int(*pa)[4] = new int[3][4]{ {0} };for (int i = 0; i < sizeof(int[3][4]) / sizeof(int[4]); i++){for (int j = 0; j < 4; j++){cout << pa[i][j] << "";}cout << endl;}int (*px)[3][4][5] = new int[2][3][4][5];return 0;
}

 内存释放

#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;int main()
{int *p = new int;delete p;int *q = new int[1000];delete []q;//多维只用一个框即可,内核用递归删除int *r = new int[1000][][];delete []r;return 0;
}

内联函数

内联函数inline function

介于宏函数和普通函数之间

宏函数

优点:代码内嵌,避免了函数调用。

缺点:容易产生歧义,易使text段体积增大。

普通函数

优点:一段高度抽象的逻辑,不易产生歧义,使text段体积减小。

缺点:函数调用的压栈与出栈的开销。

inline 内联函数

优点:一段高度抽象的逻辑,不易产生歧义,使text段体积减小,会进行类型检查,避免压栈与出栈的开销。

代价:增加代码段的空间

本质:以牺牲代码段空间为代价,提高程序的运行时间的效率

适用:代码体很小且频繁调用

为何不把所有函数inline?

内嵌太多,inline变成了给编译器的一种建议

只有当函数只有10行甚至更少时才会将其定义为内联函数。

#include <iostream>
using namespace std;#define SQR(i) ((i)*(i))  //宏函数int sqr(i)  //普通函数
{return i * i;
}inline int sqr(i)
{return i * i;
}int main()
{int i = 0;while(i < 5){cout<<SQR(i++)<<endl;}return 0;
}

强制类型转换

#include <iostream>
#include <stdlib.h>using namespace std;void func(int & v)
{cout<<v<<endl;
}int main()
{static_cast  对于隐式类型可以转化的,即可用此类型float a = 5.6;int b = 5;//隐式类型转换a = b;b = a;b = static_cast<int>(a);a = static_cast<float>(b);void *p; int *q;p = q;q = p;  //报错q = static_cast<int*>(p);int x = 10;int y = 3;float z = static_cast<float>(x) / y;char * pc = static_cast<char*>(malloc(100));reinterpret_cast  对于无隐式的类型转化,static_cast不可用char * p; int * q;p = reinterpret_cast<char*>(q);int a[5] = {1, 2, 3, 4, 5};int *p = (int*)((int)a+1);int *p = reinterpret_cast<int*>((reinterpret_cast<int>(a) + 1));cout<<hex<<*p<<endl;const_cast  脱常,只能应用于指针和引用const 修饰的一定不可以改const int a = 19;func(const_cast<int&>(a));dynamic_castreturn 0;
}

宏,在预处理阶段发生了替换

常量编译阶段发生了替换

常量不变

命名空间

命名空间为大型项目开发,避免命名冲突的一种机制。

:: 作用域运算符,前面要命名空间

全局无名命名空间

局部

namespace  是对全局命名空间的再次划分。

#include <iostream>using namespace std;int v = 55;  // 全局int main()
{int b = 10;  // 局部int *p = &v;cout<<v<<endl;cout<<b<<endl;cout<<::<<endl;return 0;
}

#include <iostream>using namespace std;namespace Space{int x;void func(){printf("void func");}struct Stu{int a;int b;}
}namespace Other{int x;int y;
}int main()
{Space::x = 200;cout<<Space::x<<endl;using Space::x;x = 20;cout<<x<<endl;using namespace Space;Stu s = {1, 2};cout << s.a << "---" << endl;using namespace Other;Other::x = 10;y = 20;cout<<Other::x<<y<<endl;int m, n;std::cin>>m>>n;std::cout<<m<<n<<std::endl;return 0;
}

如果有局部变量名相同,冲突

支持嵌套

#include <iostream>using namespace std;namespace Space{int a;int b;namespace Other{int m;int n;}
}int main()
{using namespace Space::Other;m = 20;return 0;
}

协作开发

#include <iostream>using namespace std;namespace Space
{int x;
}namespace Space
{int y;
}int main()
{using namespace Space;int x = 10;int y = 20;cout<<x<<y<<endl;return 0;
}

相同空间名会合并

String类

#include <iostream>using namespace std;//string 不是关键字,而是一个类int main()
{std::string str;string str("china");string str = "china";str = "good";string str2(str);cout<<str<<endl;cout<<str2<<endl;string s = "china";s[3] = 'w';cout<<s<<endl;char buf[1024];strcpy(buf, s.c_str());  //string -> char* c_str返回字符串cout<<buf<<endl;str.swap(str2);  //交换两个字符串  swap 成员函数int n = str.find('i', 0); //查找一个字符的位置,返回下标,找不到返回-1cout<<"n = "<<n<<endl;string sArray[10] = {"0","1","22","333","4444","55555","666666","7777777","88888888","999999999",};for(int i = 0; i < 10; i++){cout<<sArray[i]<<endl;}return 0;
}

总结

malloc free C库函数  ;  new delete  new[]  delete[] 关键字

new delete > malloc free

申请单变量空间

申请数组  一维  多维

#include <iostream>using namespace std;struct Str
{char *p;
};int main()
{string *ps = new string;*ps = "china";cout<<ps<<endl;   //输出地址  对象的地址cout<<*ps<<endl;  //输出值    对象的内容struct Str str = {"abcdefg"};int *pi = new int[10]{0};char **ppc = new int*[5]{NULL};  //定义指针数组int (*p)[4] = new int[3][4];return 0;
}

erase(0, npos)

从0开始,一直删除到' '位置

str.erase(0, str.find_first_not_of(' '));

下标后,往后删除

str.erase(str.find_last_not_of(' ') + 1);

#include <iostream>
#include <string.h>
#include <stdlib.h>using namespace std;int main()
{FILE *fp = fopen("aa.txt", "r+");  //打开并读取文件if(fp == NULL)return -1;vector<string> vs;char buf[1024];while(fgets(buf, 1024, fp) != NULL)  //读取文件内容{vs.push_back(buf);  // 内容接在后边}for(int i = 0; i < vs.size(); i++){cout<<vs[i]<<endl;}fclose(fp);return 0;    
}

http://www.lryc.cn/news/137775.html

相关文章:

  • 一网打尽java注解-克隆-面向对象设计原则-设计模式
  • k8s-statefulset部署myql-Nodeport方式
  • MySQL双主架构、主从架构
  • 基于微信小程序的物流管理系统3txar
  • Maven 一键部署到 SSH 服务器
  • docker搭建owncloud,Harbor,构建镜像
  • RISC-V(1)——RISC-V是什么,有什么用
  • 基于黄金正弦算法优化的BP神经网络(预测应用) - 附代码
  • Python标准库概览
  • 两个列表的最小索引总和
  • Go语言基础之切片
  • 关于java三元组的问题
  • 如何正确地设置Outlook SMTP发送电子邮件(wordpress配置)
  • 机器学习编译系列---张量程序抽象
  • python使用matplotlib实现折线图的绘制
  • 网络协议的定义、组成和重要性?
  • vue 使用print.js打印小票
  • 算法通关村第6关【白银】| 树的层次遍历问题
  • Qt与电脑管家3
  • Jmeter 快速生成测试报告
  • 消息队列——RabbitMQ(一)
  • 人工智能在机器学习中的八大应用领域
  • vue3+ts使用vue-i18n
  • 在Ubuntu上安装和设置RabbitMQ服务器,轻松实现外部远程访问
  • Redis多机实现
  • ClickHouse安装及部署
  • [HarekazeCTF2019]Easy Notes-代码审计
  • nginx-location正则
  • 微信小程序胶囊位置计算,避开胶囊位置
  • 快速指南:使用Termux SFTP通过远程进行文件传输——”cpolar内网穿透“