question about code using set_new_handler

Hi,
The following code was written based on Chapter 7-Check the return value of new- from Effective C++ (1st edition).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>

using namespace std;

typedef void (*PEHF)();


class X
{
private:
    static PEHF currentPEHF;

public:
    static PEHF set_new_handler(PEHF p);
    void * operator new (size_t size);
    static void noMoreMemory(){
        cout<< "Unable to satisfy request for memory!\n";
    }
    double vec;
};


PEHF X::currentPEHF;

PEHF X::set_new_handler(PEHF p)
{
    PEHF oldPEHF = currentPEHF;
    currentPEHF =p;
    return oldPEHF;
}

void * X::operator new(size_t size)
{
    PEHF currentHandler = ::set_new_handler(currentPEHF);
    void *memory = ::new char[size];
    ::set_new_handler(currentHandler);
    return memory;
}

int main()
{
    X::set_new_handler(X::noMoreMemory);

    X * pX = new X[11111111111];
}


In the main function I create a situation where allocation fails, and I was expecting an error message like this
Unable to satisfy request for memory! since set_new_handler was pointing to noMemory().

The problem is that I get this message instead
1
2
3
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted

which means I'm not using set_new_handler properly.

Any idea where is my mistake?
Thanks in advence


Since you're using new[], perhaps you should define X::operator new[].
thanks cire. Your hint solved the problem!
I guess I have to add abort() so that the messages doesn't repeat for each failed allocation

1
2
3
4
static void noMoreMemory(){
        cout<< "Unable to satisfy request for memory!\n";
        abort();
}
Topic archived. No new replies allowed.