fork download
  1. // kjellkod playing with temporary objects.
  2. // From Herb's Gotw: http://h...content-available-to-author-only...r.com/2013/05/09/gotw-2-temporary-objects-510/
  3. //
  4. // Cheers
  5. // KjellKod (.wordpress.com)
  6.  
  7. #include <iterator>
  8. #include <list>
  9. #include <string>
  10. #include <iostream>
  11.  
  12. using namespace std;
  13.  
  14. // no explicit keyword makes the implicit conversion possible. which can be avoided of course
  15. // with explicit employee(string str) ...
  16. struct employee {
  17. string addr;
  18.  
  19. employee(std::string str) : addr{str}{} // oops no explicit
  20. bool operator==(const employee& other) const { return (addr.compare(other.addr) == 0); }
  21. };
  22.  
  23.  
  24.  
  25. // using unnecessary copies. Possible scenario if employee is created as above
  26. // 1) i++ (probably close to zero overhead?)
  27. // 2) == operator implicit conversion from string to employee
  28. // 3) return value can be written {""}
  29. // 4) const reference to the arguments
  30. // 5) why not just use for(auto& employee : emps) instead of for(begin, !=end, ++) to avoid temp iterators
  31. //
  32. string find_addr( list<employee> emps, string name ) { // 4
  33. for( auto i = begin(emps); i != end(emps); i++ ) { // 1, 5
  34. if( *i == name ) { // 2
  35. return i->addr;
  36. }
  37. }
  38. return ""; // 3
  39. }
  40.  
  41.  
  42. string find_addr_improved( const list<employee>& emps, const string& name ) {
  43. for(auto& employee : emps) {
  44. if ( employee.addr == name) return employee.addr;
  45. }
  46. return {""};
  47. }
  48.  
  49. int main() {
  50. auto colleagues = list<employee>{{"Kjell"}, {"Jeanine"}, {"Nathaniel"}, {"John"}};
  51.  
  52. cout << find_addr(colleagues, {"Jeanine"}) << endl;
  53. cout << find_addr_improved(colleagues, {"Kjell"}) << endl;
  54.  
  55. return 0;
  56.  
  57. }
Success #stdin #stdout 0s 3032KB
stdin
Standard input is empty
stdout
Jeanine
Kjell