operator new和operator delete

从STL源码剖析中看到了operator new的使用

template<class T>
inline void _deallocate(T* buffer) {
    ::operator delete(buffer);
    //operator delete可以被重载
//    operator delete(buffer);
}

 从而开始研究一下这两个操作符

首先其实迷惑的是"::"的作用,通过以下代码测试出来了

class A {
public:
	void TT() {
		cout << "A" << endl;
	}
};
inline void TT() {
	cout<<"G"<<endl;
}
class B: public A {
public:
	void TT() {
		cout << "B" << endl;
		::TT();
	}
};

int main(int argc, char **argv) {
//	new Allocator();
	(new B())->TT();
	return 0;
}

 运行结果

B
G

 用于区分全局函数和函数内局部函数的符号。

#include <iostream>
#include <vector>
#include "2jjalloca.h"
#include <new>

using namespace std;

//inline void *operator new(size_t n) {
//    cout << "global new" << endl;
//    return ::operator new(n);
//}
//
//inline void *operator new(size_t n, const std::nothrow_t& nt) {
//    cout << "global new nothrow" << endl;
//    return ::operator new(n, nt);
//}

class Allocator {
public:
    void *operator new(size_t n) {
        cout << "allocator new" << endl;
        return ::operator new(n);
    }
    //作用域覆盖原则,即在里向外寻找operator new的重载时,
    //只要找到operator new()函数就不再向外查找,如果参数符合则通过,
    //如果参数不符合则报错,而不管全局是否还有相匹配的函数原型。
    //所以的调用new(std::nothrow) Allocator;注释这个函数是报错
    void* operator new(size_t n, const std::nothrow_t& nt) {
        cout << "allocator new nothrow" << endl;
        return ::operator new(n, nt);
    }

    void* operator new(size_t n, void *p) {
        cout << "allocator placement new" << endl;
        return p;
    }

    void operator delete(void *p) {
        cout << "allocator delete" << endl;
        return ::operator delete(p);
    }
    void operator delete(void*, void*) {
        cout << "allocator placement delete" << endl;
    }

    void* operator new[](size_t n) {
        cout << "allocator new[]" << endl;
        return ::operator new[](n);
    }
};

int main(int argc, char **argv) {
//    Allocator *a = new Allocator;
//    delete a;
//    ::new Allcator;

    Allocator *a=new Allocator[10];
    return 0;
}


 参考文章

C++ 内存分配(new,operator new)详解 (有些和我尝试的不一样,第四节可以着重参考)

少壮不识cpp,老大方知cpp可怕
原文地址:https://www.cnblogs.com/Jacket-K/p/9337131.html