Overloading operator delete

  • Thread starter Senthilvel Samatharman
  • Start date
S

Senthilvel Samatharman

I am just curious about the case 3 in the follwouing program.
I understand that case 1 is the right way to overload,
while Case 2 is erroneous.

But i do think that the implementation of operator delete of Case 3 should
end up in recursion but works fine.
Am i wrong or is it the problem with the VC6 compiler?

thanks ,
Senthil.

#include <iostream>

using namespace std;

class Test
{
private:
int s;
public:
Test(){
cout<<"Test::Test()"<<endl;
}


// Case 1 : This works fine
void * operator new(size_t size)
{
return ::eek:perator new (size); // Use global operator new
}

// This also works fine
void operator delete(void* p)
{
::eek:perator delete(p); // Global operator delete
}

/**************************************************************/

// Case 2 : This causes infinite recursion
void * operator new(size_t size)
{
return operator new (size); // Use local operator new
}


// This causes infinite recursion
void operator delete(void* p)
{
operator delete(p); // Use local operator delete
}

/**************************************************************/
// Case 3 : This causes a compile error
void * operator new(size_t size)
{
return new(size); // Use local new operator inside "operator new"
}

// Case 3: This does not cause a compile error or does not cause a
recursion.
void operator delete(void* p)
{
delete p;
}

};

int main()
{
Test* pTest = new Test;
delete pTest;

return 0;
}
 
N

Nick Hounsome

Senthilvel Samatharman said:
I am just curious about the case 3 in the follwouing program.
I understand that case 1 is the right way to overload,
while Case 2 is erroneous.

But i do think that the implementation of operator delete of Case 3 should
end up in recursion but works fine.
Am i wrong or is it the problem with the VC6 compiler?

thanks ,
Senthil.

#include <iostream>

using namespace std;

class Test
{
private:
int s;
public:
Test(){
cout<<"Test::Test()"<<endl;
}
[snip]

// Case 3: This does not cause a compile error or does not cause a
recursion.
void operator delete(void* p)
{
delete p;

This is ok because you are deleting a void* NOT a Test*

Consider:
void operator delete(void* p)
{
void* x = new int;
delete x; // you wouldn't expect this to recurse would you
x = p;
delete x; // what's the difference? None!
delete (Test*)p; // Now THIS is recursive
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,294
Messages
2,571,518
Members
48,225
Latest member
JasminOrta

Latest Threads

Top