使用新的算子作为函子/函数指针

问题描述 投票:2回答:1

在C ++ 11中,假设我有一个使用函子/函数并将其参数转发给该函数的函数。我可以传递一个指向std::make_shared的指针,这使它实例化一个类并调用其构造函数。但是,等效于用原始的operator new执行此操作又是什么呢?似乎std::allocator是我应该使用的,但是那里的construct函数需要一个指向分配的内存的指针。我可以通过将new调用包装到模板函数new_object中来使其工作,但是似乎应该可以直接检索该函数指针。

这是我到目前为止所拥有的:

#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;
}
c++11 functor allocator
1个回答
0
投票

为什么不这样?

   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");
© www.soinside.com 2019 - 2024. All rights reserved.