Skip to content

Instantly share code, notes, and snippets.

@trainman419
Created May 16, 2014 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trainman419/d8cf0c0f17dc05a8f940 to your computer and use it in GitHub Desktop.
Save trainman419/d8cf0c0f17dc05a8f940 to your computer and use it in GitHub Desktop.
Don't store the result of std::min in a const &
#include <stdio.h>
#include <algorithm>
class B {
public:
int b_;
B(int b) : b_(b) {}
~B() { b_ = 23; }
bool operator<(const B & o) const {
return b_ < o.b_;
}
};
int main() {
const B & m = std::min(B(3), B(5));
printf("min %d\n", m.b_);
return 0;
}
@jbohren
Copy link

jbohren commented May 18, 2014

More like "don't pass temporaries into std::min and expect to use a reference to the result"

#include <stdio.h>
#include <algorithm>

class B {
  public:
    int b_;

    B(int b) : b_(b) {}
    ~B() { b_ = 23; }

    bool operator<(const B & o) const {
      return b_ < o.b_;
    }
};

int main() {
  B b3(3);
  B b5(5);
  const B & m = std::min(b3,b5);
  printf("min %d\n", m.b_);
  return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment