Search code examples
c++11functorallocator

Using operator new as a functor/function pointer


In C++11, let's say I have a function that takes a functor/function and it forwards the arguments to that function. I can pass in a pointer to std::make_shared, which causes it to instantiate a class and call its contructor. But what is the equivalent to doing this with a raw operator new instead? It seems like std::allocator is what I should use, but the construct function there requires a pointer to the allocated memory. I can make it work by wrapping the new call into the template function new_object, but it seems like there should be a way for me to retrieve that function pointer directly.

This is what I have so far:

#include <iostream>
#include <memory>

struct foo
{
    foo(int i, const std::string& s)
    {
        std::cout << "i = " << i << " s = " << s << std::endl;
    }
};

template <typename F, typename... Args>
void do_something(F f, Args&&... args)
{
    f(std::forward<Args>(args)...);
}

// Is there a way to avoid this wrapper and handing a function pointer to
// something like ::new<foo, int, std::string> directly? Similar to std::make_shared<foo>?
template <typename C, typename... Args>
C* new_object(Args&&... args)
{
    return new C(std::forward<Args>(args)...);
}

int main()
{
    do_something(std::make_shared<foo, int, std::string>, 1, "test1"); // This works
    do_something(new_object<foo, int, std::string>, 12, "test2");
    return 0;
}

Solution

  • Why not something like this?

       std::allocator<foo> alloc;
       do_something(std::bind(&std::allocator<foo>::construct<foo, int, std::string>, &alloc, alloc.allocate(sizeof(foo)), std::placeholders::_1, std::placeholders::_2), 12, "test2");