網站首頁 編程語言 正文
1. new 和 delete?
在C++
中,動態的分配對象和釋放對象我們使用的是new
和 delete
那么,new
和 delete
與 c
語言中的 malloc
和 free
有什么區別呢?
我們為什么又要使用new
和 delete
呢?
首先 在C++中,把 new
和 delete
改成了關鍵字;
new
主要做三件事:調用operator new
分配空間、初始化對象、返回指針。
這個時候,就體現出new
和 malloc
的區別來了,初始化對象,且返回的是一個該類的對象指針。
malloc
只是單純的分配空間, 其他的事,一律不管。
若要用malloc
體現出new
的價值,大抵可以這樣寫一下(我自己的拙見)
template<typename T, typename ...PACK> T *NEW(PACK... pack) { T *tmp = (T *) malloc(sizeof(T)); // 調用 malloc分配指針 tmp->T::init(pack...); // 初始化對象 return tmp; // 返回指針 }
示例類
struct E { int x, y; void init() {this->x = 0;this->y = 0;} void init(int x) { init(); this->x = x; } void init(int x, int y) { init(); this->x = x;this->y = y; } void print() {cout << x << " " << y << endl;} void add(const E &rsh) { this->x += rsh.x; this->y += rsh.y; } };
使用
auto tmp1 = NEW<E>(1); auto tmp2 = NEW<E>(1, 2); tmp1->print(); tmp2->print();
不夠像的地方: 因為類調用不了自身的構造函數,構造函數的隱式調用的。 所有我采用了一個init函數來充當我的偽構造函數。(反正分配內存時也沒調用構造函數嘛)
三種 new
拋異常的 new
void *operator new(std::size_t count) throw(std::bad_alloc);
try { const long long N = 10e18; auto p = new int8_t[N]; delete p; } catch (std::bad_alloc &bad) { cout << bad.what() << endl; }
不拋異常的 new
void *operator new(std::size_t count, const std::nothrow_t&) throw();
long long N = 10e18; auto p = new(std::nothrow) int8_t[N]; assert(p);
palcement new
在已有的內存上構建,不重新分配內存
struct E { int x, y; }; auto mall = ::malloc(100); auto p = new(mall) E{.x = 1, .y = 2}; int32_t *now = static_cast<int32_t *>(mall); cout << *now << endl; cout << *++now << endl; free(mall);
對于第三種,很有意思,相當于把 分配內存和構造分開的設計
是不是有點眼熟?
啊對對對
就是alloctor的搞法嘛。
有時候構造操作是一個比較耗時的操作,這個時候就有用了
struct E { int x, y; E(int x = 0, int y = 0) : x(x), y(y) {} void print() { cout << x << " " << y << endl; } void add(const E &rsh) { this->x += rsh.x; this->y += rsh.y; } }; template<typename T> T *allocate() { return static_cast<T *>(::malloc(sizeof(T))); } template<typename T, typename ...PACK> T *construct(void *ptr, PACK... pack) { return new(ptr) T(pack...); } signed main() { auto t = allocate<E>(); t = construct<E>(t, 1, 2); t->print(); return 0; }
2. operator new 和 operator delete
operator new
就是一個運算符了,且我們可以重載這個運算符,使其分配內存的方式是我們自定義的分配方式。
比如重載 operator new
來給 new
用
struct E { E() { cout << "construct" << endl; } void *operator new(std::size_t length) { cout << "malloc object" << endl; return ::malloc(length); } void *operator new[](std::size_t length) { cout << "malloc array" << endl; return ::malloc(length); } void operator delete(void *now) { cout << "free object" << endl; ::free(now); } void operator delete[](void *now) { cout << "free array" << endl; ::free(now); } }; signed main() { auto t = new E; auto tarray = new E[2]; delete t; delete[] tarray; } /* output malloc object construct malloc array construct construct free object free array */
3. 重載 operator new 和 operator delete 有什么用啊? 有用?
當然,是有用的。在某些時候,可能重載分配方式可能是一個比較好的選擇
眾所周知,若是頻繁的分配一些小對象又釋放的,這樣子的操作是不好的。
雖然操作系統可以幫我們干一些臟活累活,可是,若是根據性能瓶頸分析,發現問題出在分配小對象上面,這個時候我們就可以考慮整個內存池了。(內存分配策略是個大活,我這里的代碼只是簡單示例)
使用 內存池
struct E { int arr[100]; void *operator new(std::size_t size); void operator delete(void *ptr); }; struct ENode { void *node; ENode *next; }; const int MAX_LENGTH = 1024; ENode *poll = nullptr, *use = nullptr; auto init = []() -> bool { auto now = poll; for (int i = 0; i < MAX_LENGTH; i++) { if (i == 0) poll = now = new ENode{.node = malloc(sizeof(E)), .next = nullptr}; else { auto pre = now; now = new ENode{.node = malloc(sizeof(E)), .next = nullptr}; pre->next = now; } } return true; }(); void *E::operator new(std::size_t size) { assert(poll != nullptr); auto now = poll; poll = poll->next; now->next = use; use = now; return now->node; } void E::operator delete(void *ptr) { assert(use != nullptr); auto now = use; use = use->next; now->next = poll; poll = now; poll->node = ptr; }
auto t = std::chrono::high_resolution_clock::now(); E *arr[1024]; for (int i = 0; i < 1000; i++) { for (int j = 0; j < 1024; j++) { arr[j] = new E; } for (int j = 0; j < 1024; j++) { delete arr[(j + i) % 1024]; } } cout << (std::chrono::high_resolution_clock::now() - t).count() << endl;
不使用內存池
struct W { int arr[100]; };
auto t = std::chrono::high_resolution_clock::now(); W *arr[1024]; for (int i = 0; i < 1000; i++) { for (int j = 0; j < 1024; j++) { arr[j] = new W; } for (int j = 0; j < 1024; j++) { delete arr[(j + i) % 1024]; } } cout << (std::chrono::high_resolution_clock::now() - t).count() << endl;
對比結果
在上述測試中, 使用內存池的時間穩定在 7.5 ms
左右
不使用內存池穩定在 108 ms
左右
當然,我這個測試是片面的,在這里,我只是想說明,重載 operator new
和 operator delete
的用途與好處
原文鏈接:https://juejin.cn/post/7134293115145289758
相關推薦
- 2022-08-17 yolov5中anchors設置實例詳解_python
- 2022-02-01 uniapp 開發h5 優化加載速度
- 2021-10-12 shell實現Fisher–Yates?shuffle洗牌算法介紹_linux shell
- 2022-09-02 Python+OpenCV實現基本的圖像處理操作_python
- 2024-03-18 SpringBoot + Mybatis 多數據源配置打印SQL失效問題(mybatis.confi
- 2022-06-25 Qt一個進程運行另一個進程的實現方法_C 語言
- 2022-06-16 C++新特性詳細分析基于范圍的for循環_C 語言
- 2022-12-14 Python中shape[0]、shape[1]和shape[-1]分別的意思詳解(附代碼)_pyt
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支