考虑以下代码,其中使用std::function三次捕获一个类的方法:
struct some_expensive_to_copy_class
{
void foo1(int) const { std::cout<<"foo1"<<std::endl; }
void foo2(int) const { std::cout<<"foo2"<<std::endl; }
void foo3(int) const { std::cout<<"foo3"<<std::endl; }
};
struct my_class
{
template<typename C>
auto getFunctions(C const& c)
{
f1 = [c](int i) { return c.foo1(i);};
f2 = [c](int i) { return c.foo2(i);};
f3 = [c](int i) { return c.foo3(i);};
}
std::function<void(int)> f1;
std::function<void(int)> f2;
std::function<void(int)> f3;
};然而,这将执行类some_expensive_to_copy_class的三个副本,正如人们所猜测的那样,这是效率低下的。
是否有一种解决办法,只复制一份?
为了强调这一点,我在这里感兴趣的是使用std::function的方法,而不是void-pointers,也不是相应的基于继承的实现。
发布于 2016-01-15 21:42:21
使用shared_ptr创建一个副本,并捕获它。
auto spc = std::make_shared<const C>(c);
f1 = [spc](int i) { return spc->foo1(i); }
f2 = [spc](int i) { return spc->foo2(i); }
f3 = [spc](int i) { return spc->foo3(i); }https://stackoverflow.com/questions/34820217
复制相似问题