Sign in to follow this  

Refrences and Temporaries, or Why Does This Work?

This topic is 2056 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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:

[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()
[/CODE]

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

[CODE]
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 (?)
[/CODE]

Share this post


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

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

Share this post


Link to post
Share on other sites
[quote name='Red Ant' timestamp='1335301565' post='4934545']
[quote name='Ripiz' timestamp='1335301295' post='4934543']
Possibly it's an optimization causing object to be allocated on the local stack [...]
[/quote]

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 [i]could [/i]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).

Share this post


Link to post
Share on other sites
[url="http://llvm.org/demo/index.cgi"]clang's compiler[/url].

[quote]
/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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Note that the life of the object could have been extended through a constant reference.

See the [url="http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/"]GOTW article on the subject[/url].

Share this post


Link to post
Share on other sites
No, that only applies to actual temporaries bound to a const reference. Since BrokenFoo() returns a reference and not a value, a const reference can't keep the original object alive.

Share this post


Link to post
Share on other sites
[quote]
... undefined behaviour begins as soon as I dereference the null pointer ...
[/quote]
Of course, in general one doesn't even have that guarantee. The compiler might re-order the program, which could result in the undefined behaviour manifesting itself at "unexpected" times (though if one tries to expect a certain behaviour from a non-compliant program then one is sure to be disappointed sooner or later).

Share this post


Link to post
Share on other sites
[quote]I was expecting an AV, or some sort of exception.[/quote]

Both of those are artefacts of OS or compiler, they aren't needed in general case.

Access violation is triggered when process attempts to access part of memory it didn't allocate with sufficient permissions. As far as C and C++ go, there is absolutely nothing wrong with simply writing bits and bytes anywhere into addressable memory.

Exceptions are also compiler implementation detail, but accessing memory is allowed.

To cover all uses, C and C++ must allow for this:[code]
int * p = (int*)0x22005a9c;
*p = 42;[/code]p happens to be pointing to memory mapped device and writing 42 performs some action. Stuff like that is common when working with hardware directly. Before DX, in era of VESA and such, it's how graphics were done. There's something to be said about simplicity:[code]
char * screen[80] = 0xB800; or // text buffer or 0xA000 for graphics

screen[17][25] = #; // draw # on row 17, column 25;[/code]

C++ would obviously prefer this be encapsulated somewhere, but at some level, one runs out of abstractions.

Neither C nor C++ create a perfect abstraction layer above that, meaning above functionality is always present. Java or C# however simply do not have syntactic or other constructs to make above possible.

Share this post


Link to post
Share on other sites

This topic is 2056 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this