Article View: gnu.g++
Article #304Re: Overloaded new operator in C++
From: Enno Sandner
Date: Fri, 16 Feb 1996 09:39
Date: Fri, 16 Feb 1996 09:39
71 lines
2598 bytes
2598 bytes
User Jdsmith wrote:
>
> I am experiencing a problem with overloading the
> new operator when allocating an array of classes.
>
> I do the following and my overloaded new operator is
> called as expected:
>
> ptr = new ClassThatOverloadsNew;
>
> But when I do this:
>
> ptr = new ClassThatOverloadsNew[5];
>
> The default new operator is called.
>
> What needs to be done to get an overloaded new operator to be called
> when allocating an array of data types? Does C++ even allow this
> to be done? I have checked several C++ manuals and none explicitely
> state that this can be done (and none say that it cannot be done!).
> I assumed that the overloaded new operator would be called with the
> number of bytes (the first parameter) being set to:
>
> sizeof(class) * arrayCount
>
> But this is not the case. Does anybody know how to solve this problem?
> I'm sure it is supported and is simple to do, I just have not found the
> right documentation on how to do it. My assumptions have been wrong so
> far, so I need some help.
>
You have to provide array new/delete operators.
For instance, the subsequent code shows how to overload the appropriate
allocation functions for a class 'A':
>>>>
#include <iostream.h>
#include <new.h>
struct A {
void* operator new (size_t t) {
cout << "new\n";
return :: operator new(t);
}
void* operator new[] (size_t t) {
cout << "new[]\n";
return :: operator new[](t);
}
void operator delete(void* p) {
cout << "delete\n";
:: operator delete(p);
}
void operator delete[](void* p) {
cout << "delete[]\n";
:: operator delete(p);
}
};
int main()
{
delete new A;
delete[] new A[5];
return 0;
}
<<<<
When an array of objects of type 'A' is created 'A:: operator new[](size_t)' is called.
'A:: operator delete[](size_t)' is used to release the allocated memory when the array
is destructed.
Enno
Technical Details
Message-ID:
<312450B7.167EB0E7@intellektik.informatik.th-darmstadt.de>Path:
arc1-ca.pugleaf.net!news.th-darmstadt.de!newsReferences:
<4g0boe$c37@maverick.tad.eds.com>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!news.th-darmstadt.de!news From: Enno Sandner <enno@intellektik.informatik.th-darmstadt.de> Newsgroups: gnu.g++,gnu.g++.help,comp.lang.c++ Subject: Re: Overloaded new operator in C++ Date: Fri, 16 Feb 1996 10:39:03 +0100 Organization: Fachbereich Informatik, TH Darmstadt Message-ID: <312450B7.167EB0E7@intellektik.informatik.th-darmstadt.de> References: <4g0boe$c37@maverick.tad.eds.com> NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit X-Mailer: Mozilla 2.0 (X11; I; SunOS 4.1.3 sun4m)