Which case is better?

I have a MyClass list:

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

Which example of removal is better (design and execution of C ++):

 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?

PS Please, not a lambda function and not C ++ 0x.

+7
source share
2 answers

From a design point of view, the one that uses bind is definitely the clearest. (followed by an explicit function object). What for? Succinct.

In terms of performance, the function object must be unsurpassed (everything can be easily analyzed and inserted). Depending on how the compiler optimizer is optimized, it is possible that it uses bind (the call to is_old_result may or may not be via a pointer, depending on the analysis of the compiler).

+12
source

With a more suitable name, such as "IsOldResult" or "ResultOlderThan", I would say that the final solution will be the most readable, as it is most suitable for prose:

 results.remove_if(ResultOlderThan(lifetime)); 

However, I would probably just go and write a functor if the presented algorithm appeared in several contexts. Writing a 5-line class physically deleted from one site for a single-line call seems to me too wasteful.

Otherwise, the boost :: bind parameter has my vote, as it has the smallest extra fluff between it and std :: bind2nd (_1 and std :: mem_fun_ref, respectively). In addition, boost :: bind works for a larger number of cases in general, for example, in the case when you do not bind only one variable to a function that has only two parameters.

+3
source

All Articles