I have a function that looks like this:
class SomeClass {
// ...
};
void some_function(const SomeClass& arg = SomeClass());
The function some_function
accesses its argument by reference and has a default value. Is it safe to do this, or will the reference be invalid when I call the function without an argument?
Yes, it's safe. A const reference bound to a temporary extends the life of that temporary to the lifetime of the reference. The same is true of rvalue references.
It will be valid. The lifetime of the temporary used as a default value is a superset of the lifetime of the function call. This is also no different than if you had passed in a temporary explicitly (default arguments are basically syntactic sugar, saving you from typing, but behave more or less identically to arguments passed explicitly.
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