C++必知必会 - 特定于类的内存管理

本文介绍如何通过自定义C++中的operator new和operator delete来改变new和delete操作符的行为。这不仅可以帮助开发者更好地控制内存分配过程,还能实现如内存池等高级功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们无法对new操作符和delete操作符做什么,因为它们的行为是固定的,但是可以改变它们所调用的operator new和operator delete。实现方式就是在类中定义operator new和operator delete成员函数,在new操作符调用时,编译器首先会在类所在的作用域中查找operator new,如果找不到,那么将会在全局作用域中去查找。


void* operator new (std::size_t size) throw (std::bad_alloc);
void* operator new (std::size_t size, const std::nothrow_t& nothrow_constant) throw();
void* operator new (std::size_t size, void* ptr) throw();

Global dynamic storage operator functions are special in the standard library:

    All three versions of operator new are declared in the global namespace, not in the std namespace.
    The first and second versions are implicitly declared in every translation unit of a C++ program: The header <new> does not need to be included for them to be present.
    The first and second versions are also replaceable: A program may provide its own definition, that replaces the default one, to produce the result described above.

operator new can be called explicitly as a regular function, but in C++, new is an operator with a very specific behavior: An expression with the new operator, first calls function operator new with the size of its type specifier as first argument, and if this is successful, it then automatically initializes or constructs the object (if needed). Finally, the expression evaluates as a pointer to the appropriate type.


成员operator new和operator delete是静态成员函数.因为这两个函数仅仅负责获取和释放对象的存储区,因此它们用不到this指针。成员函数只有标成static才没有this指针。跟确切的说,在对象的内存被分配之前或者被释放之后,对象不处于有效状态,也没有this指针可用。

 

一个常见的误解是以为使用new和delete操作符就意味着使用堆内存,其实并非如此。使用new操作符唯一能表明的是operator new的函数将被调用,且该函数返回一个指向某块内存的指针。
没错,标准的operator new和delete使用的是堆,但是用户自定义的可以做任何事情。对于分配的内存到底来自哪里是没有限制的:堆,静态分配的块,或者一个函数的局部存储区。要说对于这个内存的来源确实存在什么限制因素的话,那就是你的创造力不够强、见识不够多。

 

参考:

http://www.cplusplus.com/reference/std/new/operator%20new/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值