operator new和operator delete
生活随笔
收集整理的這篇文章主要介紹了
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)詳解 (有些和我嘗試的不一樣,第四節可以著重參考)
?
轉載于:https://www.cnblogs.com/Jacket-K/p/9337131.html
總結
以上是生活随笔為你收集整理的operator new和operator delete的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ES6中的super
- 下一篇: wx.navigateTo的url不生效