장용연
장용연

Reputation: 9

Questions about returning const references

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

  1. The function returns a local variable by reference. Shouldn't it be lost when the function ends end the variable goes out of scope?
  2. And even if it doesn't go out of scope, since static variables are initialized only once and the function returns by reference, if you were to supply a default value with this function twice, wouldn't they be sharing same address therefore making them non-distinct?

Upvotes: 0

Views: 135

Answers (2)

paddy
paddy

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

Daniel H
Daniel H

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

Related Questions