Jump to content

  • Log In with Google      Sign In   
  • Create Account

Interested in a FREE copy of HTML5 game maker Construct 2?

We'll be giving away three Personal Edition licences in next Tuesday's GDNet Direct email newsletter!

Sign up from the right-hand sidebar on our homepage and read Tuesday's newsletter for details!


Refrences and Temporaries, or Why Does This Work?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
14 replies to this topic

#1 joshuanrobinson2002   Members   -  Reputation: 183

Like
0Likes
Like

Posted 24 April 2012 - 02:34 PM

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.

Sponsor:

#2 Ravyne   GDNet+   -  Reputation: 7725

Like
2Likes
Like

Posted 24 April 2012 - 02:47 PM

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.

#3 Red Ant   Members   -  Reputation: 461

Like
0Likes
Like

Posted 24 April 2012 - 03:00 PM

Yup, it's simply just UNDEFINED BEHAVIOR. May actually appear to work some of the time, or it may cause your computer to explode. :)

#4 Ripiz   Members   -  Reputation: 529

Like
0Likes
Like

Posted 24 April 2012 - 03:01 PM

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 (?)


#5 Red Ant   Members   -  Reputation: 461

Like
0Likes
Like

Posted 24 April 2012 - 03:06 PM

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.

#6 samoth   Crossbones+   -  Reputation: 4910

Like
0Likes
Like

Posted 25 April 2012 - 04:22 AM


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.

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

#7 Antheus   Members   -  Reputation: 2397

Like
0Likes
Like

Posted 25 April 2012 - 04:35 AM

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();


Doesn't compile.

#8 Álvaro   Crossbones+   -  Reputation: 13623

Like
0Likes
Like

Posted 25 April 2012 - 06:49 AM

Same thing with gcc:

kk.cpp:16:15: error: invalid initialization of non-const reference of type ‘Foo&’ from an rvalue of type ‘Foo’



#9 e‍dd   Members   -  Reputation: 2105

Like
0Likes
Like

Posted 25 April 2012 - 01:10 PM

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.

#10 Aardvajk   Crossbones+   -  Reputation: 6052

Like
0Likes
Like

Posted 25 April 2012 - 01:36 PM

Better example of an invalid (null) reference, again is undefined behaviour of course but the code is legal:


void f(const int &x)

{

    std::cout << x;

}



void g()

{

    int *p = 0;

    f(*p);

}



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.

#11 joshuanrobinson2002   Members   -  Reputation: 183

Like
0Likes
Like

Posted 25 April 2012 - 03:24 PM

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.

#12 frob   Moderators   -  Reputation: 22178

Like
0Likes
Like

Posted 25 April 2012 - 07:08 PM

Note that the life of the object could have been extended through a constant reference.

See the GOTW article on the subject.

Check out my book, Game Development with Unity, aimed at beginners who want to build fun games fast.

Also check out my personal website at bryanwagstaff.com, where I write about assorted stuff.


#13 SiCrane   Moderators   -  Reputation: 9623

Like
0Likes
Like

Posted 25 April 2012 - 07:12 PM

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.

#14 rip-off   Moderators   -  Reputation: 8513

Like
0Likes
Like

Posted 26 April 2012 - 08:04 AM

... undefined behaviour begins as soon as I dereference the null pointer ...

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

#15 Antheus   Members   -  Reputation: 2397

Like
1Likes
Like

Posted 26 April 2012 - 08:32 AM

I was expecting an AV, or some sort of exception.


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:
int * p = (int*)0x22005a9c;
*p = 42;
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:
char * screen[80] = 0xB800; or // text buffer or 0xA000 for graphics

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

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.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS