Reputation: 9
const Date& default_date()
{
static const Date dd{1970, 1, 1};
return dd;
}
I was reading Stroustrup's book and I just couldn't get the code above. It's about giving default values in a constructor.
The questions I have are
Upvotes: 0
Views: 135
Reputation: 63471
When you define static variables in a function, they are only constructed once: when the function is first called. Because the variable has static duration, it resides in a different area of memory, not on the stack. It will remain in memory until your program exits, at which time all locally-defined static variables are destroyed in reverse order to their creation.
If you want to read what the C++ standard says about it start here:
Upvotes: 4
Reputation: 7433
It turns out that your second question answers the first. Yes, static
local variables stick around for multiple calls of the function, which is why the reference remains valid.
As for the second, that's correct, the two references would be to the same object. Since they are const
, as is the object they reference, this usually isn't a problem.
Upvotes: 0