Originally posted by Sebastiani
I have a memory class that I really enjoy using. There are a couple of issues though:
1) Is there a way to invoke the constructor and destructor manually on items returned from the pool such that the memory is not freed, just the functions called?
Although every one knows you can not explicitly call a constructor (You can call a destructor manually though), there is a way for you to simulate it;
Code:
#include <iostream>
#include <new>
class Foo {
public:
int number;
Foo(int num) {number = num;}
};
int main()
{
const int nNum = 10;
const int nVal = 2;
//call global operator new[] to alloc
//memory without constructor calls
Foo* ptrFoo = static_cast<Foo*>
(operator new[](nNum*sizeof(Foo)));
//call placement new to call constructors
//of each object in pre-alloced memory
for(int i = 0;i < nNum;i++)
new(ptrFoo+i) Foo(nVal*i);
//Read value of each object...
for(int i = 0;i < nNum;i++){
std::cout << "Foo number " << i+1;
std::cout << " has a value of ";
std::cout << ptrFoo[i].number << std::endl;
}
//Must now make call manual call to destructor..
//maybe not needed, but to make a point
for(int i = 0;i < nNum;i++)
ptrFoo[i].~Foo();
//call operator delete[] to free memory
operator delete[] (ptrFoo);
}
Originally posted by Sebastiani
2) if a user explicitly calls delete on an item, the items contents (or rather, the chunk within the pool) should not be freed since the underlying C/C++ lookup mechanisms won't find it to be a new'd/malloc'd pointer, correct?
You need to overload operator delete to do the actual freeing, this can then alter the size of the free memory pool you have created.....the call to delete will call the object's destructor so you can leave that as is
Originally posted by Sebastiani
3) I am really trying to avoid overriding new/delete globally.
You cant overload new - new covers calls to operator new(which can be overloaded and acts like malloc - void* return and all), placement new and a static_cast to the type required.......
You can overload operator new though...
Code:
#include <cstdio>
#include <new>
#include <cstdlib>
class foobar{};
void* operator new(std::size_t size)throw(std::bad_alloc){
std::printf("%s","operator new called\n");
return std::malloc(size);
}
int main(){
int* x = new int;
foobar* foo = new foobar;
delete x;
delete foo;
}