Re: Can anybody tell me the reason
Ashu schrieb:
Geo wrote:
Ashu wrote:
can anybody tell me the reason why following code is not working?
int *funct()
{
int p=10;
return &p;
}
int *ptr;
funct() = ptr; //------->Giving Compile time error
(LValue)
[...]
Boss I think u need to study some book nd for kind information of u
all, u can assign like this
func() = ptr
If func() returns an Lvalue, you can do that.
However, a pointer by itself is an rvalue, just like an int:
int getInt() { return ... }
int* getPointer() { return ... }
int i;
getInt() = 10; // won't work
getPointer() = &i; // won't work
But a pointer can be used to form an lvalue. By dereferencing the
pointer, you get an lvalue for the pointee:
*getPointer() = 10; // works (or better: compiles)
But!! the function above is dangerous:
int *funct()
{
int p=10;
return &p;
}
This will return a pointer to a local variable, which lifetime ends by
leaving the function. If you dereference the pointer, you invoke
undefined behaviour.
You can return a pointer to a static variable, which is often used for
singletons (but I would return a reference):
class Singleton;
Singleton* getSingleton()
{
static Singleton instance;
return &instance;
}
--
Thomas