C++ Primer 5th笔记(chap 19 特殊工具与技术)定位 new 表达式
1. 定位 new (placement new)
1.1 起因
內存分配和初始化分離開
Placement new allows you to construct an object in memory that’s already allocated.
C++早期版本中,allocator類還不是標準庫一部分。應用程序調用operator new和operator delete。這兩個函數的負責分配或釋放內存空間,但是不會構造或銷毀對象。
1.2 解決
對于operator new分配的內存空間,用new的定位new形式構造對象。
new (place_address) type new (place_address) type (initializers) new (place_address) type [size] new (place_address) type [size] {braced initializer list} // place_address必須是一個指針,同時在initializers中提供一個(可能為空的)以逗號分隔的初始值列表,該初始值列表將用于構造新分配的對象。eg.
char *buf = new char[sizeof(string)]; // pre-allocated buffer string *p = new (buf) string("hi"); // placement new string *q = new string("hi"); // ordinary heap allocationeg.
we can cluster objects together in a single memory area, select an allocator which is very fast but does no deallocation, use memory mapping, and any other semantic we wish to impose by choosing the pool and passing it as an argument to an object’s placement new operator
class Pool { public:Pool() { /* implementation details irrelevant */ };virtual ~Pool() { /* ditto */ };virtual void *allocate(size_t);virtual void deallocate(void *);static Pool::misc_pool() { return misc_pool_p; /* global MiscPool for general use */ } };class ClusterPool : public Pool { /* ... */ }; class FastPool : public Pool { /* ... */ }; class MapPool : public Pool { /* ... */ }; class MiscPool : public Pool { /* ... */ };// elsewhere...void *pnew_new(size_t size) {return Pool::misc_pool()->allocate(size); }void *pnew_new(size_t size, Pool *pool_p) {if (!pool_p) {return Pool::misc_pool()->allocate(size);}else {return pool_p->allocate(size);} }void pnew_delete(void *p) {Pool *hp = Pool::find_pool(p);// note: if p == 0, then Pool::find_pool(p) will return 0.if (hp) {hp->deallocate(p);} }// elsewhere...class Obj { public:// misc ctors, dtors, etc.// just a sampling of new/del operatorsvoid *operator new(size_t s) { return pnew_new(s); }void *operator new(size_t s, Pool *hp) { return pnew_new(s, hp); }void operator delete(void *dp) { pnew_delete(dp); }void operator delete(void *dp, Pool*) { pnew_delete(dp); }void *operator new[](size_t s) { return pnew_new(s); }void *operator new[](size_t s, Pool* hp) { return pnew_new(s, hp); }void operator delete[](void *dp) { pnew_delete(dp); }void operator delete[](void *dp, Pool*) { pnew_delete(dp); } };// elsewhere...ClusterPool *cp = new ClusterPool(arg1, arg2, ...);Obj *new_obj = new (cp) Obj(arg_a, arg_b, ...);2. 顯式的析構函數調用
就像定位new與使用allocate類似一樣,對析構函數的顯式調用也與使用destroy很類似。
調用析構函數會銷毀對象,但是不會釋放內存。
string *sp = new string("a value"); // 分配并初始化一個string對象 sp->~string();和調用destroy類似,調用析構函數可以清除給定的對象但是不會釋放該對象所在的空間。如果需要的話,我們可以重新使用該空間。
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的C++ Primer 5th笔记(chap 19 特殊工具与技术)定位 new 表达式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ Primer 5th笔记(cha
- 下一篇: C++ Primer 5th笔记(cha