Cheok Yan Cheng Cheok Yan Cheng - 11 days ago 5
C++ Question

Why this is causing C2102: '&' requires l-value

I was wondering, why the following way of code (Already commented out) will cause

C2102: '&' requires l-value


Is there a better way to avoid using
tmp
variable?

class a {
private:
int *dummy;
public:
int* get_dummy() const {
return dummy;
}
};

int main()
{
a aa;

// error C2102: '&' requires l-value
//int** me = &(aa.get_dummy());

// OK!
int *tmp = aa.get_dummy();
int** me = &(tmp);
}

Answer

Because a::get_dummy() returns a unnamed temporary object (int pointer).
Object returned by function sit ontop of the stack frame and it is meaningless to get its address since it might be invalid after expression ends.

Comments