Reputation: 131
What happens to the reference in function parameter, if it gets destroyed when the function returns, then how const int *i
is still a valid pointer?
const int* func(const int &x = 5)
{
return &x;
}
int main()
{
const int *i = func();
}
Upvotes: 13
Views: 708
Reputation: 490738
§12.2/5:
"A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call."
That means as i
is being initialized, it's getting the address of a temporary object that does exist at that point. As soon as i
is initialized, however, the temporary object will be destroyed, and i
will become just another dangling pointer.
As such, yes, the function is valid -- but with the surrounding code as you've written it, any code you added afterward that attempted to dereference i
would give undefined behavior.
Upvotes: 8
Reputation: 59841
Default arguments are evaluated every time the function is called, so the call func()
is actually func(5)
which is binding a temporary to a reference-to-const. The lifetime of that temporary is then extended till the end of the function and the object is destroyed. Any pointer to this object after that is invalid and dereferencing it is undefined behaviour.
Upvotes: 0
Reputation: 6834
I think that x
is created as an un-named temporary on the stack in setting up the call to func()
. This temporary will exist until at least the end of the statement in the caller. So the int* i
is perfectly valid. It only ceases to be valid at the end of the statement - which means that you cannot use it.
There is something in the standard about un-named temporaries being retained until the last reference to them goes out of scope, but I don't think it covers this explicit and hidden indirection. [ Happy to have someone tell me otherwise.]
Upvotes: 1
Reputation: 8255
Just because a pointer has a value doesn't mean it's a valid pointer.
In this case it holds an address which used to be that of x, and chances are that address still has the value 5, but it's not valid pointer and you can't count on that value being there.
Upvotes: 3
Reputation: 20638
5 is program data. It is in the data segment, not the stack or heap.
So a pointer or reference to it will remain valid for the duration of the program.
Upvotes: 0
Reputation: 21597
the variable "i" is still a pointer, but even reading the value it points to will give you undefined behavior. That's why you should never write a function like func.
Upvotes: 1
Reputation: 3190
int i
points to a patch of memory that is unsafe to access, it is not a valid pointer.
Upvotes: 1