Is it possible to overload the new operator so that an object isn’t created, but instead return an existing object.
If that is possible, how could you create the objects in the first place 😀
This sounds weird I know. I’m trying to hide some details from the client. I am making a game on PS2, I’d like to have the New Foo() syntax but want a list of premade objects that can be used instead.
I don’t see to circumvent this as the new operator returns a pointer to available memory.
new Foo;
struct Foo
{
void* operator new(std::size_t)
{
// return pre made obj.
}
};
You can overload
operator new, but that overloaded operator doesn’t return an object. It returns the memory for an object, and the implementation arranges for the constructor to be called.So you can’t do quite what you want.
Instead, if the cost you’re trying to avoid is that of memory allocation, then your overload can assign some memory from a pre-allocated block. Obviously you’re then responsible for tracking what’s free and what isn’t, and your challenge is to do this more efficiently than the allocator that comes with the PS2 devkit. That might not be too hard – you have an unfair advantage if you’re only dealing with one class, and assuming nobody derives from it, that the size of the allocations is fixed.
If the cost you’re trying to avoid is that of calling the constructor, then
operator newdoesn’t help you, but you could write a sort of wrapper: