Refrences and Temporaries, or Why Does This Work?

Started by
12 comments, last by Antheus 11 years, 11 months ago
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.
Advertisement
Note that the life of the object could have been extended through a constant reference.

See the GOTW article on the subject.
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.

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

This topic is closed to new replies.

Advertisement