#include<iostream>
#include<utility>
#include<tuple>
#include<functional>
using namespace std;
int main()
{
int i = 0;
auto p = make_pair(ref(i), ref(i++));
p.first++;
p.second++;
cout << "i = " << i << endl;
}
For example if I use ref() like this, the compiler will say
use of deleted function 'void std::ref(const _Tp&&) [with _Tp = int]'
however if my code is following
#include<iostream>
#include<utility>
#include<tuple>
#include<functional>
using namespace std;
int main()
{
int i = 0;
auto p = make_pair(ref(i), ref(++i));
p.first++;
p.second++;
cout << "i = " << i << endl;
}
I will successfully get the output i = 3, so I can't understand why I get so different answers.
std::ref takes a variable and gives you something that acts like a reference to that variable.
i++ is not a variable; it is a temporary. That's because of how post-increment works; the original value is incremented but the expression evaluates to the old value, and a temporary is required to hold that old value so you can read it.
std::ref doesn't allow you to use a temporary, in order to avoid mistakes like this one. It would be a dangling reference, otherwise.
++i, on the other hand, just gives you back the original variable, so you can take a reference to that just fine.
However, you can't put i and ++i right next to each other like that; the two expressions are indeterminately sequenced (or something) with respect to each other. Avoid this kind of code at all costs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With