0
class A
{
...
}

A foo()
{
    A fooA;
    return fooA;
}

int main()
{
    A &a = foo();
    return 0;
}

Here is the simple code. I test this in VS2013. there are no error or warning. I think foo() function return temporary of "fooA". That is rvalue. In g++, error occur in "A &a = foo();". In error message, it must be "const A &a". I think g++ is right. And I don't know why VS2013 could compile it?

seung hwan Son
  • 183
  • 1
  • 7
  • Looks like it is a duplicate of [Non-const reference bound to temporary, Visual Studio bug?](http://stackoverflow.com/q/16380966/1708801) ... yup if you use `/Za` this will turn into an error so looks like a duplicate. – Shafik Yaghmour Dec 09 '14 at 15:01
  • The object `fooA` must be allocated in top of `foo()`s stack. And in this way I don't see where the object will 'live' when assigned to `a` reference. The original `fooA` is already destroyed and `a` is reference, not real object - i.e. it points to somewhere. But this `somewhere` is the stack which is overwritten. It looks more realistic if you write `A a = foo();`. – i486 Dec 09 '14 at 15:05
  • @ShafikYaghmour: Correct, thanks for finding it. – MSalters Dec 09 '14 at 15:07
  • @i486 But you are creating a copy by returning it per-value. `fooA` may be destroyed, but it's returned copy lives on :) – filmor Dec 09 '14 at 15:10
  • Ok, but where is the memory for this copy after `&a` assignment? If `a` was object, not reference, it would have its stack frame. But when reference it expects to point to somebody else's memory. – i486 Dec 09 '14 at 15:12
  • @Shafik Yaghmour: Nice~ vs Language extension is the problem. Thank you – seung hwan Son Dec 09 '14 at 16:00

1 Answers1

-1

It is simply a language extension of the Microsoft.:)

You should set off these extensions in the properties of a MS VC++ project.

I described some such confusing behaviour of the MS C++ compiler in my personal forum in thread MS VC++ 2010: when a bug is not a bug but a language extension Though it is written in Russian but you can translate it in English using for example google service translate.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335