考虑以下代码,其中 std::function
被使用了 3 次以捕获一个类的方法:
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
指针,也不是相应的基于继承的实现。
最佳答案
使用 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); }
关于C++ 类型删除,用 std::function 捕获单个类的多个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34820217/