You can do that if you use a helper class whose destructor takes care of the ++(*this);
part.
struct IncrementMinder
{
IncrementMinder(foo* fPtr) : fPtr_(fPtr) {}
~IncrementMinder() { ++(*fPtr_); }
foo* fPtr_;
}
foo operator++(int) {
InrementMinder minder(this);
return *this;
// Destructor of minder takes care of ++(*this)
}
I think your test is not properly framed. A better demonstration of the concept is as below:
#include <iostream>
struct foo {
struct IncrementMinder
{
IncrementMinder(foo* fPtr) : fPtr_(fPtr) {}
~IncrementMinder() { ++(*fPtr_); }
foo* fPtr_;
};
foo(int val) : value(val) {}
// Not correct.
// When a reference is returned, const or otherwise, the calling function
// will get a reference to the object, which will be incremented by the
// time the reference is used in the calling function.
// const foo& operator++(int) {
foo operator++(int) {
IncrementMinder minder(this);
return *this;
// Destructor of minder takes care of ++(*this)
}
foo& operator++() {
++value;
return *this;
}
operator int() {
return 0;
}
int value;
} bar{20};
void f(const foo& bar) { std::cout << "bar.value: " << bar.value << "\n"; }
int main()
{
f(bar);
std::cout << "Using post-increment...\n";
f(bar++);
f(bar);;
std::cout << "Using pre-increment...\n";
f(++bar);
f(bar);
}
Output with g++ -std=c++14
:
bar.value: 20
Using post-increment...
bar.value: 20
bar.value: 21
Using pre-increment...
bar.value: 22
bar.value: 22
Live Demo.