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

c++中的匿名对象及内存管理及模版初阶

c++中的匿名对象

A a;//a的生命周期在整个main函数中
a.Sum(1);
//匿名对象生命周期只有一行,只有这一行会创建对象,出了这一行就会调析构
A().Sum(1);//只有这一行需要这个对象,其他地方不需要。
return 0;

日期到天数的转换 

计算日期到天数转换_牛客题霸_牛客网根据输入的日期,计算是这一年的第几天。 保证年份为4位数且日期合法。 进阶:时。题目来自【牛客题霸】icon-default.png?t=N7T8https://www.nowcoder.com/practice/769d45d455fe40b385ba32f97e7bcded?tpId=37&&tqId=21296&rp=1&ru=/activity/oj&qru=/ta/huawei/question-ranking

深入理解析构

#include <iostream>
#include <vector>
using namespace std;

int main() {
    //vector<int> getMouthDays{0,31,28,31,30,31,30,31,31,30,31,30,31};
    static int getMouthDays[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
    int year,mouth,day;
    while(cin>>year>>mouth>>day)
    {
        int n=0;
        for(int i=1;i<mouth;++i)
        {
            n+=getMouthDays[i];
        }
        n+=day;
        if(mouth>2&&((year%4==0&&year%100!=0)||(year%400==0)))
            n++;
        cout<<n<<endl;;
    }
    return 0;
}
// 64 位输出请用 printf("%lld")
C c;
int main()
{
	A a;
	B b;
	static D d;
	return 0;
}

构造顺序:C A B D

析构顺序:B A D C

static 修饰后(局部静态对象)第一次执行时才会调用构造 (初始化)。

全局的在main函数之前构造。

局部对象先析构,全局对象和静态对象在析构。

static D d;程序结束时才会销毁。

深入理解拷贝构造

 拷贝构造也是构造,写了拷贝构造编译器就不会生成构造了。

Widget v(u);
Widget w=v;

Widget w=v;

w存在:调operator赋值

w不存在:调拷贝构造

编译器不优化一个f(x) 调四次拷贝构造。最后共9次。

 内存管理

int globalVar = 1;
 static int staticGlobalVar = 1;
 void Test()
 {
    static int staticVar = 1;
    int localVar = 1;
    
    int num1[10] = {1, 2, 3, 4};
    char char2[] = "abcd";
    char* pChar3 = "abcd";
    int* ptr1 = (int*)malloc(sizeof (int)*4);
    int* ptr2 = (int*)calloc(4, sizeof(int));
    int* ptr3 = (int*)realloc(ptr2, sizeof(int)*4);
    free (ptr1);
    free (ptr3);
 }

char2是一个5个字节的数组整个数组都存在栈上。

全局变量和static变量的区别;

 链接属性不同

int globalVar = 1;
 static int staticGlobalVar = 1;

 执行main函数前就完成初始化。

    static int staticVar = 1;

当前文件可见 

int globalVar = 1;

 所有文件可见

运行到这个位置就初始化。

int globalVar = 1;

malloc/calloc/realloc的区别

malloc:申请空间

calloc:申请空间+初始化为0

realloc:对以有的空间进行扩容

int* p1=new int(10);
int* p2=new int[10];

delete p1;
delete[] p2;

new和delete的意义?

对于内置类型申请的效果是一样的

对于自定义类型来说有区别

A* a = new A;//申请空间+调构造函数初始化
A* a2 = (A*)malloc(sizeof(A));
cout << a->_a << endl;
cout << a2->_a << endl;

delete a;//释放空间+调析构函数

operator new与operator delete函数

new和delete是用户进行动态内存申请和释放的操作符,operator new 和operator delete是系统提供的 全局函数,new在底层调用operator new全局函数来申请空间,delete在底层通过operator delete全局 函数来释放空间。

/*
operator new:该函数实际通过malloc来申请空间,当malloc申请空间成功时直接返回;申请空间失败,
尝试执行空 间不足应对措施,如果改应对措施用户设置了,则继续申请,否则抛异常。
*/
void *__CRTDECL operator new(size_t size) _THROW1(_STD bad_alloc)
{
 // try to allocate size bytes
 void *p;
 while ((p = malloc(size)) == 0)
 if (_callnewh(size) == 0)
 {
 // report no memory
 // 如果申请内存失败了,这里会抛出bad_alloc 类型异常
 static const std::bad_alloc nomem;
 _RAISE(nomem);
 }
 
 return (p);
}
 
/*
operator delete: 该函数最终是通过free来释放空间的
*/
void operator delete(void *pUserData)
{
 _CrtMemBlockHeader * pHead;
 
 RTCCALLBACK(_RTC_Free_hook, (pUserData, 0));
 
 if (pUserData == NULL)
 return;
 
 _mlock(_HEAP_LOCK); /* block other threads */
 __TRY
 
 /* get a pointer to memory block header */
 pHead = pHdr(pUserData);
 
 /* verify block type */
 _ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));
 
 _free_dbg( pUserData, pHead->nBlockUse );
 
 __FINALLY
 _munlock(_HEAP_LOCK); /* release other threads */
 __END_TRY_FINALLY
 
 return;
}
 
/*
free的实现
*/
#define free(p) _free_dbg(p, _NORMAL_BLOCK)

对比malloc和new operator

    size_t size=2;
	void* p4=malloc(size*1024*1024*1024);
	cout<<p4<<endl;

malloc申请失败返回0

	try
	{
		void* p5=operator new(2*1024*1024*1024);
		cout<<p5<<endl;		
	}
	catch(exception& e)
	{
		cout<<e.what()<<endl;
	}

使用方式一样处理错误方式不一样。

new operator更符合面向对象的方式。

 

 定制operator new 和 operator delete

void* operator new(size_t n)
 {
 void* p = nullptr;
 p = allocator<ListNode>().allocate(1);
 cout << "memory pool allocate" << endl;
 return p;
 }
 
 void operator delete(void* p)
 {
 allocator<ListNode>().deallocate((ListNode*)p, 1);
 cout << "memory pool deallocate" << endl;
 
 }
};

定位new/replacement new

对已经存在的一块空间调用构造函数初始化

	A* p2=(A*)operator new(sizeof(A));
	new(p2)A(10);
	p2->~A();
	operator delete(p2);

格式:new(空间指针)类型参数

int的范围 -2^31-2^32-1

申请4G空间

x64:

	size_t size=2;
//	void* p4=malloc(size*1024*1024*1024);
//	cout<<p4<<endl; 
//	
	try
	{
		char* p5= new char[2*1024*1024*1024];
		cout<<p5<<endl;		
	}
	catch(exception& e)
	{
		cout<<e.what()<<endl;
	}

模版初阶 

函数模版 

目录

c++中的匿名对象

日期到天数的转换 

深入理解析构

深入理解拷贝构造

 内存管理

全局变量和static变量的区别;

malloc/calloc/realloc的区别

new和delete的意义?

operator new与operator delete函数

对比malloc和new operator

 定制operator new 和 operator delete

定位new/replacement new

模版初阶 

函数模版 


template<class T>
void Swap(T& x1,T&x2)
{
	T x=x1;
	x1=x2;
	x2=T;
}

我们不能调用函数模版,调用的是函数模版实例化生成的对应类型的函数

 预处理时生成。

 

 

 


http://www.kler.cn/news/283661.html

相关文章:

  • 【系统架构师软考】计算机网络知识(四)
  • 在类Unix操作系统(如Linux)上运行Windows应用程序方法小记
  • flutter和原生Android以及IOS开发相比有什么优缺点?
  • Gradio学习——图像流输出
  • ShenNiusModularity项目源码学习(3:用户登录)
  • MFC工控项目实例之七点击下拉菜单弹出对话框
  • Python使用总结之Flask-SocketIO介绍
  • 查看显卡cuda版本
  • PD协议沟通过程
  • 最大池化、非线性激活、线性层
  • 【C++ Qt day3】
  • PrimeVue DataTable 属性值解析
  • validationtools中按键测试选项光标移除
  • JavaEE 第18节 TCPUDP优缺点(对比)
  • 基于SVM的手势识别,SVM工具箱详解,SVM工具箱使用注意事项
  • 【策略方法】设计模式:构建灵活的算法替换方案
  • 已经git push,但上传的文件超过100MB
  • 都2024了,还在为uniapp的app端tabbar页面闪烁闪白而发愁吗
  • AI:引领未来的科技浪潮
  • 基于vue框架的餐馆管理系统jo0i7(程序+源码+数据库+调试部署+开发环境)系统界面在最后面。
  • 解决Vite+Vue3打包项目本地运行html白屏和报错问题
  • 【iOS】Masonry学习
  • EasyCode实现完整CRUD + 分页封装
  • RateLimiter超时
  • Memcached stats items 命令
  • JVM运行时数据区详解
  • 全球视角下的AI应用:国内外技术与实践的比较分析
  • 了解一下 CSS 的了解font-variant-alternates属性
  • TCP/IP和SNMP
  • matlab峰值检测