1

I am confused whether in the following snippet foo is guaranteed to be valid, i.e., whether I am allowed to store function return values as const references?

I am asking because the return value is stored on a stack-frame, which might be invalid soon after the value was returned.

Foo getFoo() {
   return Foo();
}

void bar() {
  const auto& foo = getFoo();

  // more function calls...

  // is foo guaranteed to be valid?
}
user695652
  • 4,105
  • 7
  • 40
  • 58
  • 1
    Yes, it is valid. – Edgar Rokjān Oct 17 '16 at 19:20
  • I wanted to emphasize a different aspect of the question. The one marked as duplicate and Herb Sutter's link don't really address the memory perspective. I am really curious as to why the referenced object don't get's overwritten when new stackframes are allocated. – user695652 Oct 17 '16 at 19:26
  • I suppose it's an implementation defined feature. – Edgar Rokjān Oct 17 '16 at 19:29
  • @user695652: Wanting to understand how this works is a different question (which might very well have been answered already); after checking whether it is already asked (I advise using google to search SO, much better than the internal search engine), and if it has not, you are welcome to ask the question. Note that the standard only specifies how things should behave, not how they are implemented, so if you have a specific toolchain in mind you might want to specify it in case different toolchains use different strategies. – Matthieu M. Oct 18 '16 at 10:55

1 Answers1

3

It is valid C++, however be aware that some compilers (e.g. Visual Studio 2015, as far as I know) do not implement it properly.

According to the standard (N4140):

12.2 Temporary objects
....

4 There are two contexts in which temporaries are destroyed at a different point than the end of the fullexpression. The first context is when a default constructor is called to initialize an element of an array. If the constructor has one or more default arguments, the destruction of every temporary created in a default argument is sequenced before the construction of the next array element, if any.

5 The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:

(some exceptions)

AlexD
  • 32,156
  • 3
  • 71
  • 65