Help with "error: non-lvalue in unary `&'"
Hi, here's the situation: I have a template class, one of its method returns the type specified in the template (see Entry<T>::getData()). Problem is, I can't convert its return type to pointer. In method "cetak", the lines: "T* ptr = &(v[0]->getData())" produces compile error: "error: non-lvalue in unary `&'". If, I change the line to: "T* ptr = &(v[0]->data), I got no error. =========================================== #include <iostream> #include <vector> using namespace::std; template<typename T> class Entry { public: T getData() const; T data; }; template<typename T> T Entry<T>::getData() const { return data; } typedef Entry<int> ei; template<typename T> void cetak(int i, const vector<ei*>& v) { T* ptr = &(v[0]->getData()); //<------- Error here. //T* ptr = &(v[0]->data) //<-------- This one success. cout << ptr << endl; cout << *ptr << endl; } int main() { vector<ei*> v; ei* ONE = new ei(); ONE->data = 1; v.push_back(ONE); cetak<int>(0, v); return 0; } =========================================== -- -- Verdi March --
On Friday 18 July 2003 12:28, Verdi March wrote:
here's the situation: I have a template class, one of its method returns the type specified in the template (see Entry<T>::getData()).
Problem is, I can't convert its return type to pointer. In method "cetak", the lines: "T* ptr = &(v[0]->getData())" produces compile error: "error: non-lvalue in unary `&'".
And the compiler is perfectly right - as usual ;-) getData() returns a temporary object of type T. It exists only for the duration of this expression's evaluation - it's gone after that line T* ptr = &(v[0]->getData()); Just think of it: getData() creates a temporary object in it's 'return' statement. The call to getData() gets this object so it can do something with it - but when the expression to the right of the '=' is finished evaluating, the temporary object is destroyed, so its address is no longer valid. This is what the compiler means to tell you. If on the other hand you use T* ptr = &(v[0]->data); you return the address of the 'data' member of that 'v[0]' object which still exists after that line. CU -- Stefan Hundhammer <sh@suse.de> Penguin by conviction. YaST2 Development SuSE Linux AG Nuernberg, Germany
On Friday 18 July 2003 18:56, Stefan Hundhammer wrote:
And the compiler is perfectly right - as usual ;-)
getData() returns a temporary object of type T. It exists only for the duration of this expression's evaluation - it's gone after that line
Thanks, you're right. Using int (instaed of T) also produces the same compile error. At first I thought it was something to do with template. -- -- Verdi March -- -- -- Verdi March --
participants (3)
-
Cincai Patron
-
Stefan Hundhammer
-
Verdi March