2

I'm using the RTL as a dynamic library. This allows for an overridden new/delete operator in global namespace, because the linker would find my implementation first. I could rely on malloc() and free() to do the allocation stuff, but there are things like 'new_handlers' and 'std::nothrow' objects. Standard library templates require a certain behaviour of the new/delete operators, but the standard library's implementation of new/delete in global namespace is out of scope! Is there an implementation in another namespace from the standard libary that I can use?

I might dynamically determine the address of the standard library's impementation (in the dll) and call it through a pointer, but that's not subject to a beauty reward. Still would this work? (I am using borland C++ builder 2006).

EDIT I want to ask this question:

Does this sample code behave similar to RTL's operator new(size_t)? Or did I missunderstand it?

void *new_replacement(size_t p_size)
{
    void *l_retval = NULL;

    while(l_retval == NULL && p_size != 0)
    {
        l_retval = malloc(p_size);
        if (l_retval == NULL)
        {
            void (*l_handler)() = std::set_new_handler(NULL);

                                 // could not find another way to obtain the current new_handler
            if (l_handler == NULL) throw std::bad_alloc();
            std::set_new_handler(l_handler);
            l_handler();
        }
    }
    return l_retval;
}
rene
  • 41,474
  • 78
  • 114
  • 152
bert-jan
  • 958
  • 4
  • 15

1 Answers1

2

You've replaced, not overridden the default implementation and you no longer can call it. You will have to reimplement it - for example by using malloc() and taking care of its return value, it's not very hard.

Community
  • 1
  • 1
sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • Then is would use the option to call it through a pointer. There are just too much things to thing of to write my own impementation. – bert-jan Jul 15 '11 at 12:36
  • If it's not hard, would you give some code example how to do it like the std-rtl does it? – bert-jan Jul 15 '11 at 12:40
  • 1
    @bert-jan: This answer http://stackoverflow.com/questions/4134195/how-do-i-call-the-original-operator-new-if-i-have-overloaded-it/4134355#4134355 describes it in details. – sharptooth Jul 15 '11 at 12:43
  • I suppose the new_handler function takes care of throwing the std::bad_alloc object unless there are std::nothrow objects around in the current thread. Is this true? – bert-jan Jul 15 '11 at 12:51
  • 1
    @bert-jan: No, this question http://stackoverflow.com/q/5548639 lists usages of `new_handler()`. – sharptooth Jul 15 '11 at 12:53
  • @bert-jan: `new` is not allowed to return a null pointer. Your `operator new()` will return a null pointer if passed null size. Other than that it looks good. – sharptooth Jul 15 '11 at 14:06