什么情况比较好?
我有一个 MyClass
列表:
struct MyClass {
bool is_old_result(int lifetime);
};
std::list<MyClass> results;
int lifetime = 50; // or something else
什么情况下删除更好(c++ 设计和性能):
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));
,为什么?
PS 请不要使用 lambda 函数,也不要使用 C++0x。
I have a list of MyClass
:
struct MyClass {
bool is_old_result(int lifetime);
};
std::list<MyClass> results;
int lifetime = 50; // or something else
What case of removing is better (c++ design and perfomance):
results.remove_if(
std::bind2nd(std::mem_fun_ref(&MyClass::is_old_result), lifetime));
or
results.remove_if(boost::bind(&MyClass::is_old_result, _1, lifetime));
or
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));
and why?
P.S. Please, no lambda-function and no C++0x.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从设计上来说,使用
bind
的绝对是最清晰的。 (后面是显式函数对象)。为什么?简洁。在性能方面,函数对象应该是无与伦比的(一切都可以轻松分析和内联)。根据编译器的优化方式,使用
bind
的可能会匹配它(对is_old_result
的调用可能会也可能不会通过指针,具体取决于编译器的分析)。In terms of design, the one using
bind
is definitely the clearest. (followed by the explicit function object). Why? Succinct.In terms of performance, the function object should be unbeatable (everything can be easily analysed and inlined). Depending on how the compiler optimizes, the one using
bind
could possibly match it (the call tois_old_result
may or may not be through a pointer, depending on the compiler's analysis).如果有更合适的命名,例如“IsOldResult”或“ResultOlderThan”,我会说最终的解决方案将是最具可读性的,因为它是最适合散文的解决方案:
但是,我可能只会去写函子如果它所代表的算法出现在多个上下文中。对我来说,编写一个从其单行调用站点中物理删除的 5 行类似乎过于浪费。
否则, boost::bind 选项得到了我的投票,因为它和 std::bind2nd (分别是 _1 和 std::mem_fun_ref )之间的附加绒毛最少。此外,boost::bind 通常适用于更多情况,例如您不只绑定只有两个参数的函数的一个变量的情况。
With more suitable naming, such as "IsOldResult" or "ResultOlderThan", I would say that the final solution would be the most readable, as it is the one that most passes for prose:
However, I would probably only go and write the functor if the algorithm it represented turned up in multiple contexts. Writing a 5-line class that is physically removed from its single one-liner call site seems overly wasteful, to me.
Otherwise, the boost::bind option has my vote since it has the least additional fluff between it and std::bind2nd (_1 and std::mem_fun_ref, respectively). In addition, boost::bind works for more cases in general, such as a case where you are not binding only one variable of a function that has only two parameters.