栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

[c++简易笔记] new 和 delect

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

[c++简易笔记] new 和 delect

-我不去想,是否能够成功 ,

-既然选择了远方 ,便只顾风雨兼程。

目录

new 和 delect 的使用 

 1.operator new与operator delete函数

1-1 operator new与operator delete函数 代码实现分析

1-2 测试用例比较

 1-3  operator new与operator delete的类专属重载(了解)

 2.new 和 delete

2-1测试代码:

2-2 汇编粗略解析

 2-3 new 和delect 代码分析

3.定位new表达式(placement-new)

-------------------------------------------------------------------------------------

参考资料:


new 和 delect 的使用 
// 动态申请一个int类型的空间

 int* ptr1 = new int;
 
 // 动态申请一个int类型的空间并初始化为10
 int* ptr2 = new int(10);
 
 // 动态申请10个int类型的空间
 int* ptr3 = new int[3];
 
 delete ptr1;
 delete ptr2;
 delete[] ptr3;

//注意:申请和释放单个元素的空间,使用new和delete操作符,申请和释放连续的空间,使用new[]和delete[]



// 申请Test类型的对象
class Test{
public:
    Test()
     : _data(0)
    {
     cout<<"Test():"< 

 1.operator new与operator delete函数

1-1 operator new与operator delete函数 代码实现分析
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);
}

void operator delete(void *pUserData)
{
    _CrtMemBlockHeader * pHead;
    RTCCALLBACK(_RTC_Free_hook, (pUserData, 0));
    
    if (pUserData == NULL){
        return;
   
    _mlock(_HEAP_LOCK); 
    
    __TRY
 
        
         pHead = pHdr(pUserData);
 
        
         _ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));

         _free_dbg( pUserData, pHead->nBlockUse );

    __FINALLY

         _munlock(_HEAP_LOCK); 

    __END_TRY_FINALLY
 
    
    return;
}

#define free(p) _free_dbg(p, _NORMAL_BLOCK)

1-2 测试用例比较
int main(){
    // operator new() 申请空间
    Stack* ps1 =(Stack*) operator new (sizeof(Stack));
    operator delete(ps1);

    //malloc() 申请空间
    Stack* ps2 = (Stack*)malloc(sizeof(Stack));
    assert(ps2);    // 区别::  malloc 需要检查,operator new不需要!
    free(ps2);    


    //你也可以一次性申请更大的空间,然后触发异常,这里就不做演示
    //这段代码的目的主要是为了体会 operator new()  和malloc() 的区别
}
通过观察代码(或测试用例可以发现)::
          operator new() =malloc() + 抛异常
        operator delet() =free() +抛异常

 1-3  operator new与operator delete的类专属重载(了解)
struct ListNode{
	ListNode* _next;
	ListNode* _prev;
	int _data;
	
    void* operator new(size_t n){
		void* p = nullptr;
		p = allocator().allocate(1);
		cout << "memory pool allocate" << endl;
		return p;
	}
	void operator delete(void* p){
		allocator().deallocate((ListNode*)p, 1);
		cout << "memory pool deallocate" << endl;
	}
};


class List{
public:
	List(){
		_head = new ListNode;
		_head->_next = _head;
		_head->_prev = _head;
	}
	~List(){
		ListNode* cur = _head->_next;
		while (cur != _head){
			ListNode* next = cur->_next;
			delete cur;
			cur = next;
		}
		delete _head;
		_head = nullptr;
	}

private:
	ListNode* _head;
};

int main(){
	List l;
	return 0;
}

 2.new 和 delete

2-1测试代码:
class Stack
{
public:
	Stack(int capacity = 0)
	{
		cout << "Stack(int capacity)" << endl;
		_a = new int[capacity];
		_capacity = capacity;
		_top = 0;
	}

	~Stack()
	{
		cout << "~Stack()" << endl;
		delete[] _a;
		_capacity = 0;
		_top = 0;
	}

	void Push(int x)
	{}
private:
	int* _a;
	int _top;
	int _capacity;
};

class MyQueue {
public:
	//MyQueue()
	//	: _pushST(4)
	//	, _popST(4)
	//{}
private:
	Stack _pushST;
	Stack _popST;	//用于查看对自定义类型的处理情况

};

int main()
{
	// Stack st;
	//Stack* ps1 = (Stack*)malloc(sizeof(Stack));
	ps1->Stack();
	//assert(ps1);
	//Stack* ps2 = new Stack; // 开空间+调用构造函数初始化

	//free(ps1);
	//delete ps2; // 调用析构函数清理资源 + 释放空间

	MyQueue* obj = new MyQueue;

	delete obj;



	return 0;
 }

2-2 汇编粗略解析

 2-3 new 和delect 代码分析

同样,通过观察我们也可以发现

        new = operator new()+ 调用构造函数  

        delete = 调用析构函数 + operator delete()

同理:

new T[N]的原理

        1. 调用operator new[]函数,在operator new[]中实际调用operator new函数完成N个对象空间的申请

        2. 在申请的空间上执行N次构造函数

delete[]的原理

        1. 在释放的对象空间上执行N次析构函数,完成N个对象中资源的清理

        2. 调用operator delete[]释放空间,实际在operator delete[]中调用operator delete来释放空间

3.定位new表达式(placement-new)

定位new表达式是在已分配的原始内存空间中调用构造函数初始化一个对象。
使用格式:
        new (place_address) type或者new (place_address) type(initializer-list)
        place_address必须是一个指针,initializer-list是类型的初始化列表
使用场景:
        定位new表达式在实际中一般是配合内存池使用。因为内存池分配出的内存没有初始化,所以如果是自定义类型的对象,需要使用new的定义表达式进行显示调构造函数进行初始化。

int main()
{
	//int* p = new int[10];
	//delete p;

	//stack* starray = new stack[10];
	//delete starray;

	stack* obj = (stack*)operator new(sizeof(stack));
	// 针对一个空间,显示调用构造函数初始化
	new(obj)stack(4);

	return 0;
}

--------------------------------------------------------------------------------------

参考资料:

关于_autoclassinit2 的探索p

ps:由于本人才疏学浅,必有不足之处,还请大佬们多多指教!

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1012574.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号