fork download
  1. #include <iostream>
  2.  
  3. struct foo {
  4.  
  5. struct IncrementMinder
  6. {
  7. IncrementMinder(foo* fPtr) : fPtr_(fPtr) {}
  8. ~IncrementMinder() { ++(*fPtr_); }
  9. foo* fPtr_;
  10. };
  11.  
  12. foo(int val) : value(val) {}
  13.  
  14. // Not correct.
  15. // const foo& operator++(int) {
  16. foo operator++(int) {
  17. IncrementMinder minder(this);
  18. return *this;
  19. // Destructor of minder takes care of ++(*this)
  20. }
  21.  
  22. foo& operator++() {
  23. ++value;
  24. return *this;
  25. }
  26.  
  27. operator int() {
  28. return 0;
  29. }
  30.  
  31. int value;
  32.  
  33.  
  34. } bar{20};
  35.  
  36. void f(const foo& bar) { std::cout << "bar.value: " << bar.value << "\n"; }
  37.  
  38. int main()
  39. {
  40. f(bar);
  41.  
  42. std::cout << "Using post-increment...\n";
  43.  
  44. f(bar++);
  45. f(bar);;
  46.  
  47. std::cout << "Using pre-increment...\n";
  48.  
  49. f(++bar);
  50. f(bar);
  51. }
  52.  
Success #stdin #stdout 0s 15232KB
stdin
Standard input is empty
stdout
bar.value: 20
Using post-increment...
bar.value: 20
bar.value: 21
Using pre-increment...
bar.value: 22
bar.value: 22