#include <cstdio>
#include <cstdlib>
#include<iostream>
#include <iterator>
using namespace std;
/****************************************************************/
//为什么语言已经有malloc,free还要有new,delete
//c++推荐使用new和delete
struct ListNode_c{
int _val;
struct ListNode *next;
struct ListNode *pre;
};
typedef struct ListNode_c ListNode_c;
ListNode_c * BuyListNode_c(int val){
ListNode_c * listnode_c = (ListNode_c *)malloc(sizeof(ListNode_c));
listnode_c->_val=val;
return listnode_c;
}
struct ListNode_cpp
{
int _val;
struct ListNode_cpp * _next;
struct ListNode_cpp * _pre;
ListNode_cpp(int val =0):_val(val),_next(nullptr),_pre(nullptr)
{
}
};
// void test01()
// {
// //ListNode_c* listnode_c1 = BuyListNode_c(1);
// //ListNode_c* listnode_c2 = BuyListNode_c(2);
// struct ListNode_cpp* node3= new ListNode_cpp(8);
// cout<<node3->_val<<endl;
// }
/****************************************************************/
/**************************operator new 与 operator delete**************************************/
class A{
public:
A(int a =0):_a(a) {
cout<<"A()"<<endl;
}
~A()
{
cout<<"~A()"<<endl;
}
private:
int _a;
};
void test02()
{
/*
* new operator
使用方式都一样 ,处理错误的方式不太一样
*/
A *p1 = (A*)malloc(sizeof(A));
A* a2 = new A();
A *a3 = (A*)operator new (sizeof(A));
}
/****************************************************************/
/****************************************************************/
//malloc free
//new ==》 operator new +构造函数 delete
//operator new =》 malloc +失败抛异常 operator delete
//new比malloc不一样的地方 1.调用构造函数自动化 2.失败了抛异常
//delete 比起free不一样的地方 1.调用析构函数清理
//operator free 和 free m没有区别
void test03()
{
//指针申请的空间不会自动消失
A *a=new A();
delete a;
//想模拟上面的行为
A *p2 = (A*)operator new(sizeof(A));
new(p2)A(10);//new(空间的指针)类型(参数)
p2 ->~A();
operator delete(p2);
}
/****************************************************************/
/****************************************************************/
/*
malloc 与new 的区别
1.new会调用构造函数,失败时抛异常,malloc失败了返回0
2.malloc是一个函数,new是一个操作符
3.malloc用法:参数传字节数,返回值是void* ,new后面跟对象的类型,返回值是类型的指针
*/
/*
c++
内存泄漏
*/
void test04()
{
char *p = new char[1024*1024*1024];
//忘记释放,最后越来越多,内存泄漏
}
/****************************************************************/
/****************************************************************/
/*
模板的出现 泛型编程 跟类型无关
解决重载过度
模板的原理
模板会进行实例化
*/
template <typename T> //模板参数 --》类型
void Swap(T& a, T& b)
{
T x= a;
a=b;
b=x;
}
void test05()
{
//下面调用的不是同一个函数
int a =0,b= 1;
Swap(a, b);
//cout<<"a:"<<a<<" b:"<<b<<endl;
double da =1.0,db=2.3;
Swap(da, db);
}
void test06(int n){
for(int i = 0; i<n; i++)
{
int *a=(int *)malloc(sizeof(int)*1000000);
for(int j =0; j<=n; j++)
{
}
}
}
/****************************************************************/
int main()
{
int n =200000;
test06(n);
cout<<"endl"<<endl;
return 0;
}
c++ day09
最新推荐文章于 2024-07-25 10:17:46 发布