Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning/Initializing references in function args

Tags:

c++

I am from C background and trying to understand what this means:

void f(const string &x = "hello") {
}

Is x set to a default value if nothing is passed in? Where does "hello" reside?

like image 483
tvr Avatar asked Aug 24 '26 01:08

tvr


1 Answers

Your parameter (x) is created/initialized in the context of the calling function. The string literal `"hello" has static storage duration.

The standard doesn't specify the form of memory in which either of those is stored, but in a typical case, the string literal will reside in some memory that's initialized directly from data in the executable file, and x will be created on the stack (with the address of the literal passed to initialize it if you don't pass something else in its place).

like image 81
Jerry Coffin Avatar answered Aug 26 '26 16:08

Jerry Coffin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!