How to use GC_malloc and then call the constructor in C ++?

I use Boehm garbage collection in C ++. How to call constructor after allocation using GC_malloc?

SomeClass *i = new SomeClass(); // Here the constructor is called.
SomeClass *j = (SomeClass *)GC_malloc(sizeof(SomeClass)); // How to call the constructor here?
+4
source share
2 answers

You want to perform a new placement.

SomeClass *j = (SomeClass *)GC_malloc(sizeof(SomeClass));
new (j) SomeClass();

This assumes that the allocator has returned properly aligned memory.

Using a garbage collector with C ++ can be error prone, as the sweeping step of the memory is unlikely to cause destructors of the objects to which the memory must belong. It would be safer to use a smart pointer like std::unique_ptror std::shared_ptr.

+4
source

In SomeClassreload operator newas follows:

void* operator new(size_t size)
{
    return GC_malloc(size);
}

SomeClass operator new, GC_malloc, SomeClass.

SomeClass operator delete :

void operator delete(void* ptr)
{
    assert(0);
}

, , assert(0); , , , SomeClass* SomeClass delete operator, SomeClass, new operator, Boehm.

0

All Articles