How do I overload the new operator to accept a std::string parameter?
Hello. I'm a C++ newbie.
I'm trying to do something very brave and beyond my capability.
The code should explain what I'm trying to do. How would I overload the "new" operator so as to allow a string to be passed in and placed in the allocated memory?
Code:
#include <cstddef>
#include <cstdlib>
#include <exception>
#include <iostream>
#include <new>
#include <string>
void * operator new (std::size_t size, std::string debug_name)
{
if (size + sizeof(std::string) < size)
{
std::bad_alloc exception;
throw exception; /* size overflow */
}
void * p = std::malloc(size + sizeof(std::string));
std::string *pstr = (std::string *) p;
*pstr = debug_name;
return p + sizeof(std::string);
}
class invalid_ptr : public std::exception {};
void operator delete(void *ptr)
{
if (ptr == NULL || ptr == nullptr)
return;
void *ptr2 = ptr - sizeof(std::string);
if (ptr2 > ptr)
{
invalid_ptr exception;
throw exception;
}
std::free(ptr2);
}
int main()
{
int *pi = new int;
*pi = 42;
std::cout << *pi << std::endl;
delete(pi);
}