什么案例更好?

时间:2010-12-14 14:39:54

标签: c++ performance stl language-design functor

我有MyClass的列表:

struct MyClass {
     bool is_old_result(int lifetime);
};
std::list<MyClass> results;
int lifetime = 50; // or something else

删除的情况更好( c ++ design and perfomance ):

results.remove_if(
    std::bind2nd(std::mem_fun_ref(&MyClass::is_old_result), lifetime));

results.remove_if(boost::bind(&MyClass::is_old_result, _1, lifetime));

struct RemoveFunctor {
   RemoveFunctor (int lifetime) : lifetime(lifetime) {}
   bool operator()(const MyClass & m) { return m.is_old_result(lifetime); }
private:
   int lifetime;
};
results.remove_if(RemoveFunctor(lifetime));

为什么?

P.S。请,没有lambda函数,没有C ++ 0x。

2 个答案:

答案 0 :(得分:12)

在设计方面,使用bind的人绝对是最清楚的。 (后跟显式函数对象)。为什么?简洁。

在性能方面,功能对象应该是无与伦比的(一切都可以轻松分析和内联)。根据编译器如何优化,使用bind的那个可能匹配它(对is_old_result的调用可能会也可能不会通过指针,具体取决于编译器的分析。)

答案 1 :(得分:3)

使用更合适的命名,例如“IsOldResult”或“ResultOlderThan”,我会说最终的解决方案是最具可读性的,因为它是最常用于散文的那个:

results.remove_if(ResultOlderThan(lifetime));

然而,如果它所表示的算法在多个上下文中出现,我可能只会编写仿函数。写一个从单个单线呼叫站点中移除的5行课程对我来说似乎过于浪费。

否则,boost :: bind选项具有我的投票权,因为它与std :: bind2nd(分别为_1和std :: mem_fun_ref)之间的附加漏洞最少。另外,boost :: bind一般适用于更多情况,例如你不绑定只有两个参数的函数的一个变量。