Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to access a default argument by reference?

Tags:

c++

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?

like image 646
Jesper Avatar asked May 01 '11 20:05

Jesper


2 Answers

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.

like image 104
Puppy Avatar answered Oct 13 '22 19:10

Puppy


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.

like image 23
BeeOnRope Avatar answered Oct 13 '22 20:10

BeeOnRope