Boost logo

Boost :

From: Andreas Brinck (Andreas.Brinck_at_[hidden])
Date: 2005-06-01 12:52:21


Hi,

I'm working on an application where we wan't to serialize objects with overloaded operator new/delete. After reading at the library homepage that it isn't possible I decided to take a look at the library code and found the following code snippet in iserializer.hpp:

template<class T>
struct heap_allocator
{
    #if 0
        // note: this fails on msvc 7.0 and gcc 3.2

        <snip>

        static T * invoke(){
            return new_operator(has_op_new(static_cast<T *>(NULL)));
        }
    #else
        // while this doesn't handle operator new overload for class T
        static T * invoke(){
            return static_cast<T *>(operator new(sizeof(T)));
        }
    #endif
};

Since we're using msvc 7.1 i decided to enable the disabled code and see what happened. The code didn't compile but after fixing some trivial compile errors I ended up with the following version:

template<class T>
struct heap_allocator
{
    #if defined(_MSC_VER) && (_MSC_VER >= 1310)
        // note: this fails on msvc 7.0 and gcc 3.2
        template <class U, U x> struct test;
        typedef char* yes;
        typedef int* no;
        template <class U>
        static yes has_op_new(U*, test<void* (*)(std::size_t), &U::operator new>* = 0) {return 0;}
        static no has_op_new(...) {return 0;}

        template<class U>
        static void * new_operator(U);

        static void * new_operator(yes){
            return (T::operator new)(sizeof(T));
        }
        static void * new_operator(no){
            return (operator new(sizeof(T)));
        }
        static T * invoke(){
            return static_cast<T *>(new_operator(has_op_new(static_cast<T *>(NULL))));
        }
    #else
        // while this doesn't handle operator new overload for class T
        static T * invoke(){
            return static_cast<T *>(operator new(sizeof(T)));
        }
    #endif
};

which at least in our project compiles, links and works just fine. I sent the change to Robert Ramey and he said he would examine it but I thought I would consult the members of this list as well. Does this work as expected or are there any hidden gotchas?

Regards

/Andreas Brinck
###########################################

This message has been scanned by F-Secure Anti-Virus for Microsoft Exchange.
For more information, connect to http://www.f-secure.com/


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk