Refrences and Temporaries, or Why Does This Work?

Started by
12 comments, last by Antheus 11 years, 12 months ago
The other day, I had one of our new developers asking me how he could get a null reference in C++. Now, I know enough about C++ to know I'm not an expert, but I felt comfortable fielding that question. I explained that a reference in C++ could not be null, but that it was possible to have an invalid reference if, for example, you return a reference to a temporary. To illustrate, I wrote the following simple code:


#include <iostream>

using namespace std;

class Foo
{
int _bar;
public:
Foo() : _bar(0) { }
int Bar() { return _bar; }
void SetBar(int value) { _bar = value; }
}; //end class

Foo& BrokenFoo()
{
return Foo();
} //end f()

int main()
{
Foo& f = BrokenFoo();
f.SetBar(10);
cout << f.Bar() << endl;
system("PAUSE");
} //end f()


Imagine my surprise when, not only did the application not throw an exception but the output was 10.

What gives? We were using Visual Studio 2008. When we built the application in Debug Mode the output was -858993460, and in both cases we got a compiler warning, and I know I've hunted down this very bug more than once in the past. But, it the application seemed to allow it. I was expecting an AV, or some sort of exception.
Advertisement
Why do you think you'd get something so nice as an exception? Neither references nor pointers do any kind of checking, they certainly don't know about how the stack works.

This code *doesn't work* -- it *happens* to work here, and even then probably only sometimes. Huge difference.


More-specifically, you don't get an Access Violation because your app owns its own stack -- the whole thing, whatever was allocated to it, regardless of what's in use.

The value is still 10 because you haven't called any other functions to used that stack space.

throw table_exception("(? ???)? ? ???");

Yup, it's simply just UNDEFINED BEHAVIOR. May actually appear to work some of the time, or it may cause your computer to explode. :)
Possibly it's an optimization causing object to be allocated on the local stack, therefore memory isn't invalid.

According to debugger, it sets value to -858993460 when you call f.Bar().
While in release mode it simply pushes 0Ah into the stack, your object is gone completely.

Either way, if you add destructor, debugger clearly shows you enter constructor and destructor inside BrokenFoo(), so whatever gets returned is invalid.


00F08D99 lea ecx,[ebp-44h]
00F08D9C call Foo::Foo (0F05B59h) // create
00F08DA1 mov dword ptr [ebp-4Ch],eax
00F08DA4 mov eax,dword ptr [ebp-4Ch]
00F08DA7 mov dword ptr [ebp-48h],eax
00F08DAA lea ecx,[ebp-44h]
00F08DAD call Foo::~Foo (0F0653Bh) // destroy
00F08DB2 mov eax,dword ptr [ebp-48h] // set return value (?)

Possibly it's an optimization causing object to be allocated on the local stack [...]


What optimization? Where else would it be "allocated" if not on the stack? Foo() creates a temporary. Of course it's on the stack.

[quote name='Ripiz' timestamp='1335301295' post='4934543']
Possibly it's an optimization causing object to be allocated on the local stack [...]


What optimization? Where else would it be "allocated" if not on the stack? Foo() creates a temporary. Of course it's on the stack.
[/quote]Well, since the structure wraps a single integer and you do not take its address, it could be in a register. When you throw code like this at GCC with full optimizations, it usually flattens out all the structures and function calls, I'd not assume any other modern compiler does much worse.

What's funny though is that such code would be perfectly allowable (i.e. correct) if the reference was const (not sure if doing a const cast for calling the non-const setter function would be "allowable", though).
clang's compiler.


/tmp/webcompile/_5317_0.cc:14:11: error: non-const lvalue reference to type 'Foo' cannot bind to a temporary of type 'Foo'
return Foo();[/quote]

Doesn't compile.
Same thing with gcc:
kk.cpp:16:15: error: invalid initialization of non-const reference of type ‘Foo&’ from an rvalue of type ‘Foo’[/quote]
As Antheus and alvaro have indicated, the code is illegal as far as the standard is concerned.

You might consider adding the following to the Visual C++ compiler command line for stricter standards compliance:

/Zc:forScope,wchar_t /we4288 /we4238 /we4239 /we4346

/we4238 or /we4239 is the relevant one in this particular case, I believe.
Better example of an invalid (null) reference, again is undefined behaviour of course but the code is legal:

[source]
void f(const int &x)
{
std::cout << x;
}

void g()
{
int *p = 0;
f(*p);
}
[/source]

But you are quite correct in your initial idea that you cannot technically have a null or invalid reference. In my code, the undefined behaviour begins as soon as I dereference the null pointer, before the reference is initialised and it is irrelevant what happens after that.

This topic is closed to new replies.

Advertisement