• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
joshuanrobinson2002

Refrences and Temporaries, or Why Does This Work?

13 posts in this topic

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.
0

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.
2

Share this post


Link to post
Share on other sites
Yup, it's simply just UNDEFINED BEHAVIOR. May actually appear to work some of the time, or it may cause your computer to explode. :)
0

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]
0

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.
0

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).
0

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.
0

Share this post


Link to post
Share on other sites
Same thing with gcc:
[quote]kk.cpp:16:15: error: invalid initialization of non-const reference of type ‘Foo&’ from an rvalue of type ‘Foo’[/quote]
0

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.
0

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.
0

Share this post


Link to post
Share on other sites
Ravyne, I expected an exception because I've seen exceptions thrown with similar code in the past. I simply assumed it would throw in this case as well, and got egg all over my face as a result :P.

Thanks for the responses everyone, I think I understand.
0

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].
0

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.
0

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).
0

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.
1

Share this post


Link to post
Share on other sites

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  
Followers 0