我们无法对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/