www.digitalmars.com         C & C++   DMDScript  

c++ - overloaded new[] and delete[] are not called

reply "Steve Strand" <snstrand comcast.net> writes:
Overloading new and delete for a class works fine, but a
redefinition of operator new[] or delete[] is ignored.
Here is a small test case:

#include <iostream.h>
#include <stdlib.h>

class test {
    int a;
public:
    test() {cout << "construct\n";}
    ~test() {cout << "destruct\n";}
    void* operator new(size_t sz) {cout << "new\n"; return malloc(sz);}
    void operator delete(void* p) {cout << "delete\n"; free(p);}
    void* operator new[](size_t sz) {cout << "new[]\n"; return malloc(sz);}
    void operator delete[](void* p) {cout << "delete[]\n"; free(p);}
};

int main() {
    test *t= new test;
    delete t;
    t= new test[4];
    delete[] t;
}

Compiled with version 8.38 the output is:
new
construct
destruct
delete
construct
construct
construct
construct
destruct
destruct
destruct
destruct

The overloaded new and delete were called as expected,
but ::new[] and ::delete[] were called instead of test::new[]
and test::delete[]. Why?
Jan 20 2004
parent reply dan <dan_member pathlink.com> writes:
In article <bul3mu$2bf3$1 digitaldaemon.com>, Steve Strand says...
Overloading new and delete for a class works fine, but a
redefinition of operator new[] or delete[] is ignored.

There's a switch to enable new[] delete[] overloads, though I'm not sure what the switch is, since I'm using the IDDE.
Jan 21 2004
parent reply Jan Knepper <jan smartsoft.us> writes:
dan wrote:
 In article <bul3mu$2bf3$1 digitaldaemon.com>, Steve Strand says...
 
Overloading new and delete for a class works fine, but a
redefinition of operator new[] or delete[] is ignored.

There's a switch to enable new[] delete[] overloads, though I'm not sure what the switch is, since I'm using the IDDE.

-Aa -- ManiaC++ Jan Knepper But as for me and my household, we shall use Mozilla... www.mozilla.org
Jan 21 2004
parent reply "Steve Strand" <snstrand comcast.net> writes:
Thanks for pointing out the -Aa flag, but unfortunately I get no difference
when I compile with -Aa or -A. Can anyone else compile my short example and
have the overloaded new[] and delete[] called?

P.S. for Walter: perhaps give an error message when -Aa is needed (like
already happens if you forget -Ae and use exceptions)
Jan 21 2004
parent dan <dan_member pathlink.com> writes:
In article <bumimm$1kaf$1 digitaldaemon.com>, Steve Strand says...
.. Can anyone else compile my short example and
have the overloaded new[] and delete[] called?

Just tried enabling the overloads in the IDDE, by clicking the check-box, but after clicking OK, if I open the settings again, the check-mark is gone. Donno what's going on; seems to me the feature's broken.
Jan 21 2004