views:

82

answers:

3

Suppose I have a class with overloaded operator new.

class Class {
public:
   void* operator new( size_t );
   void operator delete( void* );
};

Will objects of that class always be allocated with the overloaded operator new when I use new Class() or is it possible that the default operator new is used when new Class() construct appears in code?

A: 

The only possible exception I can think of is placement new (discussed here), but that's a different syntax.

jdv
+2  A: 

The overloaded operator new and operator delete will always be used unless you explicitly do something like this:

// Allocate using global new.
MyClass* my_object = ::new MyClass();

// Use object normally.
my_object->my_method();

// Deallocate using global delete.
::delete my_object;

Or, as a somewhat extreme illustrative example, something like this:

#include <new>

// Use global placement new to allocate in a buffer created by global new.
MyClass* my_object = ::new(::operator new(sizeof(MyClass))) MyClass()

// Use object normally.
my_object->my_method();

// Explicitly invoke destructor.
my_object->~MyClass();

// Explicitly deallocate memory.
::operator delete(my_object);

Hope this helps.

Jon Purdy
+5  A: 

Use scope-resolution operator (::) to call the global definition for operator new, otherwise it will always use the overloaded operator new, except ofcourse in case of placement new operator which is anyway not intended to be overloaded.

class Test {
public:
   void* operator new( size_t );
   void operator delete( void* );
};

int main()
{
Test* pTest1 = ::new Test();
Test* pTest2 = new Test();

/*
 do some stuff
*/

::delete pTest1;
delete pTest2;
return 0;
}

Note the use of corresponding definition for delete operator.

Hemant
Btw, placement new can be overloaded - http://stackoverflow.com/questions/3675059/how-could-i-sensibly-overload-placement-operator-new
sharptooth
yep, i mean OP doesn't intend to overload it in his example.
Hemant
@sharptooth: No it can't.
GMan
@sharptooth, @GMan: Placement new *is* an overload of `new`.
Jon Purdy