mjwach
mjwach

Reputation: 1214

Is there a simple, standard way to "new" and "delete" objects via an allocator?

I gather that custom allocators can sometimes be trivial to add to a program--for instance, in some particular case it may be enough to simply replace the text std::vector<int> with std::vector<int, SomeAllocator> and recompile.

But what if I want to directly replace the standard memory management with that represented by a custom allocator in code that directly uses new and delete, like this:

class Thingy
{
    int whatever;
public:
    Thingy(int whatever) : whatever(whatever) {}
};

Thingy* thingy = new Thingy(77);
delete thingy;

I am new to allocators, but I guess I can accomplish that by calling four allocator methods: one to allocate, one to construct, one to destroy, and one to deallocate.

SomeAllocatorForThingy a;
Thingy* thingy = a.allocate(1);
a.construct(thingy, 77);
a.destroy(thingy);
a.deallocate(thingy, 1);

Or something like that. But I would rather do it in two commands, like I could with new and delete; and I would like to do it without having to add that extra 1 parameter repeatedly.

Does the standard library provide a standard way to do this already? Something like:

Thingy* thingy = std::new_allocated_object<Thingy, SomeAllocatorForThingy>(77);
std::delete_allocated_object<SomeAllocatorForThingy>(thingy);

and maybe with some other forms for stateful allocators.

I don't anticipate having trouble writing my own functions for this purpose, but if standard ones already exist then I'd rather use those.

Upvotes: 0

Views: 224

Answers (1)

JustSid
JustSid

Reputation: 25318

You can override the new and delete operator as described here and here. Then you can just keep on using new and delete as is, but you'll have control over the allocation and deallocation.

Example:

class Foo
{
public:
    Foo()
    {
        std::cout << "Constructor" << std::endl;
    }

    ~Foo()
    {
        std::cout << "Destructor" << std::endl;
    }



    void *operator new(size_t size)
    {
        std::cout << "new(" << size << ")" << std::endl;
        return malloc(size);
    }

    void operator delete(void *ptr)
    {
        std::cout << "delete(" << ptr << ")" << std::endl;

        if(ptr)
            free(ptr);
    }
};

int main()
{
    Foo *bar = new Foo();
    delete bar;


    return 0;
}

Which will print something like this:

new(1)
Constructor
Destructor
delete(0x7fa72b6000a0)

Upvotes: 1

Related Questions