Why this can’t compile:
// RefToPointers.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using std::cout;
class T
{
public:
T(int* value):data_(value)
{
}
int* data_;
int* getData_()
{
return data_;
}
int getValue()//<----------Here I do not return by ref
{
return *data_;
}
};
void fnc(const int*& left, const int*& right )//<------Doesn't work even though
//it is identical to the example below just type is different. Why?
{
const int* tmp = left;
left = right;
right = tmp;
}
void fnc(const int& left,const int& right)//<---Here I pass by ref
{
}
int _tmain(int argc, _TCHAR* argv[])
{
//int* one = new int(1);
//int* two = new int(2);
//cout << "Pointers before change:" << *one << '\t' << *two << '\n';
//fnc(one,two);
//cout << "Pointers before change:" << *one << '\t' << *two << '\n';
T one(new int(1));
T two(new int(2));
fnc(one.getData_(),two.getData_());//<---This do not work
fnc(one.getValue(),two.getValue());//<<------This still works even thoug I'm
//returning by value and fnc is taking args by ref. Why does it work with int
//by not with int*?
return 0;
}
I’m getting following error:
_error C2664: ‘fnc’ : cannot convert parameter 1 from ‘int *’ to ‘int *&_
And why on earth underscores do not make font italic in line where error is listed?
getData()returns an rvalue. You can’t take a reference to an rvalue pointer.You have two choices:
1) Pass
fnc()lvalues:2) Or, since you are passing pointer references, which really are the same size as pointers themselves, why not just pass pointers?
EDIT:
A little bit more on lvalues and rvalues. “lvalue” used to mean “an expression that can be on the left of an
=operation.” rvalue was effectively the converse: an rvalue was any expression that could not be on the left of an=operation.Things are a little bit more complex than that now, but that’s still a pretty good way to understand lvalues and rvalues.
Now, consider the following code:
val()returns anintby value — in other words, it returns an unnamed temporary value. Should you be able to take the address of that temporary?You might think, “well, yeah, why not?” But the answer is actually no, you can’t take the address of the temporary. The reason has to do with the lifetime of that temporary. It’s scope is limited to the expression in which it was created. In other words:
val(). As soon asval()has been completely evaluated, the temporary ceases to exist. In effect, it falls off the stack. By the timeint* p = &is evaluated, the temporary is long gone. There’s nothing left to take the address of.This is basically why you can’t take the address of an rvalue, which by extension is why you can’t get a reference to an rvalue’s address.