473,748 Members | 2,173 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Overloading new and delete operators

There's a rather nondescript book called "Using Borland C++" by Lee
and Mark Atkinson (Que Corporation) which presents an excellent
discussion of overloaded new and delete operators.

I am presenting below a summary of what I have gathered. I would
appreciate if someone could point out to something that is specific to
Borland C++ and is not supported by the ANSI standard. I am also
concerned that some of the information may be outdated since the book
is quite old (1991 edition).
1) We cannot use the array size declarator with a class-specific
user-defined new function. Arrays of objects are always allocated
with the global new.

2) Overloaded new and delete operators should be provided in pairs.

3) Class-specific new and delete functions are always static member
functions, even though they are not explicitly declared with the
static storage class specifier.

4) A class can have many overloaded new functions ---- the correct
function is selected through best-fit signature matching, as for any
other overloaded function.

5) The first argument of each overloaded new operator is a size_t
object size argument. However, this argument is implicit and is not
provided when the overloaded new operator is invoked.

6) A class can have only one overloaded delete operator.

7) The overloaded delete operator is invoked after the last line of
the destructor has been executed.
// ~~~~~~~ Code snippet begin ~~~~~~~
#include <iostream.h>

/////////////////////////////////////////////////////////////////
class X
{
int a, b, c;

public:
~X() { cout << "Inside destructor of class X" << endl; }

// You are allowed to declare only one delete function
void operator delete( void* ptr);

// You can overload new however you want, as long as the first
// argument is always a size_t object-size argument
//
// !!!!! Important note: The size_t parameter is
// implicit. Do not write it directly into
// the function call. !!!!!
void* operator new(size_t size);
void* operator new(size_t size, void* ptr);
void* operator new(size_t size, int flag);
};
/////////////////////////////////////////////////////////////////
void* X::operator new(size_t size)
{
void* ptr;
cout << "Standard class new called.\r\n";
ptr = (void*) ::new unsigned char[size];
return ptr;
}
/////////////////////////////////////////////////////////////////
void* X::operator new(size_t size, void* ptr)
{
size = size;
cout << "Placement class new called.\r\n";
return ptr;
}

/////////////////////////////////////////////////////////////////
void* X::operator new(size_t size, int flag)
{
void* ptr;
cout << "Overloaded class new called. ";
cout << "Flag was " << flag << ".\r\n";
ptr = (void*) ::new unsigned char[size];
return ptr;
}
/////////////////////////////////////////////////////////////////
void X::operator delete( void* ptr)
{
cout << "Class delete called.\r\n";
free(ptr);
}
/////////////////////////////////////////////////////////////////
int main()
{
X* objl = new X;
// Remember the size_t parameter is implicit
// The standard class new is called
// void* X::operator new(size_t size)
delete objl;

X* obj2;
void* buf = (void*) ::new unsigned char[sizeof(X)];
obj2 = new(buf) X;
// Remember the size_t parameter is implicit
// The placement class new called
// void* X::operator new(size_t size, void* ptr)
free(buf);

X* obj3 = new(64) X;
// Remember the size_t parameter is implicit
// The overloaded class new called
// void* X::operator new(size_t size, int flag)
delete obj3;
}
// ~~~~~~~ Code snippet end ~~~~~~~

Thanks,
Nimmi
Jul 22 '05 #1
3 9409

"Nimmi Srivastav" <ni************ *@yahoo.com> wrote in message
news:8b******** *************** **@posting.goog le.com...
There's a rather nondescript book called "Using Borland C++" by Lee
and Mark Atkinson (Que Corporation) which presents an excellent
discussion of overloaded new and delete operators.

I am presenting below a summary of what I have gathered. I would
appreciate if someone could point out to something that is specific to
Borland C++ and is not supported by the ANSI standard. I am also
concerned that some of the information may be outdated since the book
is quite old (1991 edition).
1) We cannot use the array size declarator with a class-specific
user-defined new function. Arrays of objects are always allocated
with the global new.
ANSI supports overloading operator new[] and delete[] which are used for
allocating arrays. So the above is incorrect.

2) Overloaded new and delete operators should be provided in pairs.
I guess but placement delete complicates this. E.g.

class Y;
class X
{
public:
void* operator new(size_t bytes, Y*);
void operator delete(void* ptr);
void operator delete(void* ptr, Y*);
};

See, two deletes and only one new.

3) Class-specific new and delete functions are always static member
functions, even though they are not explicitly declared with the
static storage class specifier.
Correct.

4) A class can have many overloaded new functions ---- the correct
function is selected through best-fit signature matching, as for any
other overloaded function.
Correct AFAIK.Although this is usually called placement new.

5) The first argument of each overloaded new operator is a size_t
object size argument. However, this argument is implicit and is not
provided when the overloaded new operator is invoked.
It must be provided. How else would you know how much memory to allocate?
E.g.

class X
{
void operator new(size_t bytes);
};

class Y : public X
{
char big[1000];
};

Both new X and new Y will call X::operator new. But the amount of memory to
allocate is different.

6) A class can have only one overloaded delete operator.
Not correct. If you use placement new, then you should provide matching
placement deletes. These will be called of the ctor of your class throws,
IIRC.

7) The overloaded delete operator is invoked after the last line of
the destructor has been executed.


True enough.

I think you need a more up to date book.

John
Jul 22 '05 #2
"John Harrison" <jo************ *@hotmail.com> wrote in message news:<bv******* *****@ID-196037.news.uni-berlin.de>...
ANSI supports overloading operator new[] and delete[] which are used for
allocating arrays. So the above is incorrect.

Could you be kind enough to provide a code snippet for overloaded
new[] and delete[]? Can new[] and delete[] be used for instantiating
and deleting on the free store 'SINGLE ENTITIES' also, or do you need
separate methods for that? In other words, would you need four
overloaded operator methods ---- new, new[], delete & delete[]?

2) Overloaded new and delete operators should be provided in pairs.


I guess but placement delete complicates this. E.g.

class Y;
class X
{
public:
void* operator new(size_t bytes, Y*);
void operator delete(void* ptr);
void operator delete(void* ptr, Y*);
};

See, two deletes and only one new.


I am curious what you would typically do inside the body of
void operator delete(void* ptr, Y*). As always, a code snippet will
help

Not correct. If you use placement new, then you should provide matching
placement deletes. These will be called of the ctor of your class throws,
IIRC.


As mentioned above, working examples of "placement delete" would help.

Thanks and Best Regards,
Nimmi
Jul 22 '05 #3

"Nimmi Srivastav" <ni************ *@yahoo.com> wrote in message
news:8b******** *************** **@posting.goog le.com...
"John Harrison" <jo************ *@hotmail.com> wrote in message news:<bv******* *****@ID-196037.news.uni-berlin.de>...
ANSI supports overloading operator new[] and delete[] which are used for
allocating arrays. So the above is incorrect.


Could you be kind enough to provide a code snippet for overloaded
new[] and delete[]? Can new[] and delete[] be used for instantiating
and deleting on the free store 'SINGLE ENTITIES' also, or do you need
separate methods for that? In other words, would you need four
overloaded operator methods ---- new, new[], delete & delete[]?


Exactly, four methods.

Code for new[] and delete[] is exactly the same as for new and delete except
that you add []. E.g.

void* X::operator[](size_t bytes)
{
...
}


2) Overloaded new and delete operators should be provided in pairs.
I guess but placement delete complicates this. E.g.

class Y;
class X
{
public:
void* operator new(size_t bytes, Y*);
void operator delete(void* ptr);
void operator delete(void* ptr, Y*);
};

See, two deletes and only one new.


I am curious what you would typically do inside the body of
void operator delete(void* ptr, Y*). As always, a code snippet will
help


I guess typoically Y would be some sort of memory pool from which you are
allocating objects. For some reason you might want several memory pools
instead of the one large one.

Placement delete is very specialised, it is only called when the ctor of an
object you have constructed with placement new throws. To be perfectly
honest I cannot remember the reasoning behind this rule, maybe you can work
it out.

Not correct. If you use placement new, then you should provide matching
placement deletes. These will be called of the ctor of your class throws, IIRC.

As mentioned above, working examples of "placement delete" would help.


This code outputs

normal delete
placement delete

#include <iostream>
using namespace std;

class Y;

class X
{
public:
X() {} // normal ctor
X(int) { throw ""; } // throwing ctor
void* operator new(size_t bytes, Y*)
{
return malloc(bytes);
}
void operator delete(void* ptr)
{
cout << "normal delete\n";
}
void operator delete(void* ptr, Y*)
{
cout << "placement delete\n";
}
};

int main()
{
try
{
Y* y = 0;
X* p = new (y) X();
delete p;
p = new (y) X(1);
delete p;
}
catch (...)
{
}
}
Thanks and Best Regards,
Nimmi


John
Jul 22 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2022
by: HeroOfSpielburg | last post by:
I'm writing a memory manager and overloading the operators "::new" and "::delete" I know this isn't always the smartest thing to do, but regardless, I was wondering what sort of considerations I should be making when writing the array-based versions "new" and "delete" (in contrast to the single item "new" and "delete"). I know the fundamental issue between ensuring "new" is matched with "delete" is making sure the destructor for each of...
6
3662
by: Zenon | last post by:
Folks, I am having a terrible time overloading operators. I have tried what I thought was the correct way, I tried the cheating (friend declarations), all to no avail. Sorry for posting tons of code but I really need help. thanks, Zenon
3
4651
by: silver360 | last post by:
Hello, I'm trying to create a basic Heap manager and i have some question about new/delete overloading. The following code give me this output : >> $./heap >> registered : 0x804d098 >> 0x804d008 _Delete unknown block >> registered : 0x804d138 >> 0x804d008 _Delete unknown block >> 0x804d098 _Delete ok
3
385
by: md | last post by:
Hi, the following code is working for static objects. ie the statement IntArray x(20); my problem is i want to use this overloading operator for dynamically created objects for example the statement IntArray *x; Please give me some help regarding this ////////////////////////////////////////////////////////////////////////////////////////////////////////// class IntArray
9
2399
by: learning | last post by:
hi I am trying to make some simple app to learn exception safety coding. I know that new and delete can throw bad_alloc but how can I force them to throw by a flag "change" at run time? I am overloading new, new, delete and delete, change is set to 1 then it calls the custom operators. If 0, it calls the c++. But how can I overload delete and delete? The original library signature has const std::nothrow_ and throw() If I overload this,...
3
12258
by: Lighter | last post by:
The C++ Standard Doesn't Permit Overloading new and delete? In the 13.5 of The C++ standard (ISO/IEC 14882, 1998), I cannot find the specification on overloading the operators new and delete; however, many C++ books including "C++ Primer" say that the operators new and delete can be overloaded. I wonder if this has definitive specification? Who can tell me? Many thanks to those who answer.
5
3628
by: Jerry Fleming | last post by:
As I am newbie to C++, I am confused by the overloading issues. Everyone says that the four operators can only be overloaded with class member functions instead of global (friend) functions: (), , ->, =. I wonder why there is such a restriction. Some tutorials say that 'new' and 'delete' can only be overloaded with static member functions, others say that all overloading function should be non-static. Then what is the fact, and why? ...
11
4143
by: dascandy | last post by:
Hello, I was wondering, why is overloading operator. (period) forbidden? It would make a few odd applications possible (dynamic inheritance and transparent remote method invocation spring to my mind) and it would be fairly generic. The only sidecase I can see is that operator. itself would not be looked up through operator. . I read that there was previous debate on the subject, but I haven't been able to find why it was rejected.
19
2301
by: Jess | last post by:
Hello, After seeing some examples about operator overloading, I'm still a bit confused about the general syntax. The following is what I think, not sure whether it's correct. 1. For a unary operator that's a member of a class, its form is usually "operatorP()" (where P is the operator's name).
0
8991
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8831
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9552
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9376
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9249
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8245
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6796
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6076
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3315
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.