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();
}
The VALID function determines whether x , a reference to a scalar pictured value, has a value that is valid with respect to its picture specification. The result is a bit string of length one that indicates if the character-string value of x can be edited into the picture declared for x .
For something to be a function, you need one output for each input. You do not need vice versa. Your equation x2+y2=1 does not define x or y as a function of the other because (for example) if I give you an x there are 0 or 2 values for y that satisfy the equation.
Vertical lines are not functions. The equations y = ± x and x 2 + y 2 = 9 are examples of non-functions because there is at least one -value with two or more -values.
§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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With