4 hours ago, mark_braga said:
I want to prohibit the use of new, delete in one of my projects. There are still instances where I need the placement new operator to construct things like containers which need a constructor call.
So I cannot just use the old #define new Error trick.
[Edit:] Oops, I misread your original statement about needing *
placement* new, so this post doesn't actually help you.
new and delete have pretty simple implementations (based off of malloc() and free(), but with constructor/destructor calls and a few other niceties). You could grab an implementation off the web, maybe even your own compiler's copy if the licensing permits, and give them different function names (e.g. "MyDeleteFunc()").
I just tossed this together and it compiled and ran fine, though I may have made a mistake somewhere:
(feel free to take it as your own, though at your own risk =P)
namespace Memory
{
template<typename Type, typename ...Args>
Type *Allocate(Args&& ...args)
{
//Allocate memory using 'malloc'.
Type *ptr = static_cast<Type*>(malloc(sizeof(Type)));
assert(ptr && "We're probably out of memory.");
//Manually call constructor, forwarding the arguments to the constructor.
new (ptr) Type(std::forward<Args>(args)...);
//Return the pointer.
return ptr;
}
template<typename Type>
void Deallocate(Type* &ptr) //Reference to a pointer. Huh, never had to use that before.
{
//Comment this assert out if you like the ability to pass null to 'delete'.
assert(ptr && "Trying to allocate an already NULL pointer.");
//Call the destructor manually.
ptr->~Type();
//Deallocate the memory.
free(ptr);
//Nullify the pointer (we got a reference to a pointer, so this is nulling the pointer that was passed into the function).
//Comment this line out if you want to do the nulling yourself.
ptr = nullptr;
}
} //End of namespace.
Usage:
MyClass *myClass = Memory::Allocate<MyClass>("Hello", 357);
Memory::Deallocate(myClass);
Here's where I tested it.
When some people reimplement new(), they also add things like leak detection and other features.