這裏是我的應用程序的上下文:我正在使用來自不同設備的RAM的嵌入式系統。微控制器的內部RAM中有一部分(128kB),另一部分是外部RAM(1MB)。這些存儲器被映射到微控制器的地址空間,但是在不連續的區域。是否可以使用operator new從堆中分配?
內部RAM用於系統堆棧,任務堆棧和Heap。 外部RAM用於靜態分配數據(池,緩衝區和所有「static ...
」的東西)
我想實現一個簡單的內存管理結構,並作爲其中的一部分能夠創建一個allocator可能使用operator new
的分配算法,但是使用另一個內存源,而不是系統堆,而是其他地方的內存區域。你知道這是可能的嗎?
一個使用的例子可能是保留100kB的外部RAM並創建一個分配器來管理它,然後將它提供給需要這個存儲器的指定任務。
static const uint8_t* ramBase = reinterpret_cast<uint8_t*>(0x80000000);
static const uint32_t ramAreaSize = 0x19000; //100kB
BufferAllocator allocator(ramBase, ramAreaSize);
//...
//Assuming operator new is overloaded to use BufferAllocator
MyObject * obj = new (allocator) MyObject(some, parameter);
//...
的問題是:如何(如果這甚至有可能),我可以爲了使用operator new
管理原始內存區域執行BufferAllocator
?
void* BufferAllocator::allocate(uint32_t bytes)
{
//I would like to write something like this
//and so let the responsibility to manage this memory area to "new"
//so I don't have to reimplement (or reuse) a different custom
// allocator
return ::operator new(ramBase, ramAreaSize, bytes)
}
是的,這是可能的,這是正確的語法。你不能只使用'delete'來釋放對象。另一種選擇是爲'MyObject'類型重載'operator new'和'operator delete',所以你不需要使用placement new語法。 – 2015-04-01 16:40:33
這個問題:http://stackoverflow.com/questions/7194127/how-should-i-write-iso-c-standard-conformant-custom-new-and-delete-operators是一個很好的開始閱讀的地方。 – 2015-04-01 17:23:53
如果你打算使用放置新的' - >〜()'來刪除。 – jiveturkey 2015-04-01 17:37:46