日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

operator new和operator delete

發布時間:2024/9/5 编程问答 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。