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(li开发者_StackOverflow中文版fetime));
and why?
P.S. Please, no lambda-function and no C++0x.
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 to is_old_result
may or may not be through a pointer, depending on the compiler's analysis).
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:
results.remove_if(ResultOlderThan(lifetime));
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.
精彩评论