Click to See Complete Forum and Search --> : overriding new
thehustler
June 21st, 2005, 07:39 PM
I've implemented a new operator with a parameter in one of my classes as such:
class test
{
public:
static void* operator new (size_t size, int somevalue)
{
return malloc(size);
}
};
However, because I'm defining a parametered new operator, the default new operator ceases to exist and I get compiler errors if I want to instance an object using the default new.
Is there any way to keep the default new operator or do I have to redefine it manually?
Improving
June 21st, 2005, 09:06 PM
I think you either have to redefine it manually or provide default arguments for all parameters except the size_t.
Kheun
June 21st, 2005, 09:41 PM
Beside providing a default operator new, you also have to provide a corresponding operator delete.
#include <iostream>
using namespace std;
class test
{
public:
test()
{
cout << "test::test()" << endl;
}
~test()
{
cout << "test::~test()" << endl;
}
static void *operator new(size_t size, int value)
{
cout << "placement new" << endl;
return malloc(size);
}
static void *operator new(size_t size)
{
cout << "operator new" << endl;
return ::operator new(size);
}
static void operator delete(void *p, int value)
{
cout << "placement delete" << endl;
free(p);
}
static void operator delete(void *p)
{
cout << "operator delete" << endl;
::operator delete(p);
}
};
int main(void)
{
test *p1 = new(1) test;
p1->~test(); // Required to directly call the destructor because placement delete never invoke it.
test::operator delete (p1, 1);
test *p2 = new test;
delete p2;
return 0;
}
thehustler
June 21st, 2005, 09:46 PM
Yeah thanks, I was aware of that, just couldn't be bothered putting it in the example :p
I guess I just have to redefine it then.
Graham
June 22nd, 2005, 03:13 AM
Have you tried test* p = ::new test; ? (Note the scope resolution operator.)
Graham
June 22nd, 2005, 03:22 AM
Just to clarify my last answer, here's section 5.3.4/9 of the standard:
If the new-expression begins with a unary :: operator, the allocation function’s name is looked up in the global scope. Otherwise, if the allocated type is a class type T or array thereof, the allocation function’s name is looked up in the scope of T. If this lookup fails to find the name, or if the allocated type is not a class type, the allocation function’s name is looked up in the global scope. (Note that, by supplying an operator new in class scope, you are hiding the global one.)
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.