In an embedded system with two separate RAM memory areas, I have two distinct heaps (one is a custom implementation from FreeRTOS in the lower memory area, another is the heap generated by GCC in the upper memory area) and I would like to be able to choose which heap new uses.
New and Delete operators can be overloaded globally or they can be overloaded for specific classes.
In one class delete operator can be overloaded only once.
The most common reason to overload new and delete are simply to check for memory leaks, and memory usage stats. Note that "memory leak" is usually generalized to memory errors. You can check for things such as double deletes and buffer overruns.
Detailed Solution. (::) Scope resolution operator cannot be overloaded in C language. Operator overloading:- It is polymorphism in which an operator is overloaded to give user-defined meaning to it. The overloaded operator is used to perform operations on user define data type.
You could provide an operator new
overload that accepts a second argument telling it which memory area to allocate memory from. You can give arguments to operator new
by putting them in parenthesis before the type in your new-expression. This is usually used to new
an object into already-allocated storage (since that's the overload provided by the standard library), but anything can be passed there and it will be passed on to operator new
.
enum MemoryArea {
LOWER,
UPPER
};
void* operator new(std::size_t sz, MemoryArea seg) {
if (seg == LOWER) {
return allocateMemoryInLowerMemoryArea(sz);
} else {
return allocateMemoryInUpperMemoryArea(sz);
}
}
void operator delete(void* p) {
if (pointerIsInLowerMemoryArea(p)) {
freeMemoryFromLowerMemoryArea(p);
} else {
freeMemoryFromUpperMemoryArea(p);
}
}
int main() {
Foo* p = new (LOWER) Foo;
Foo* b = new (UPPER) Foo;
delete p;
delete b;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With