Note that there are some explanatory texts on larger screens.

plurals
  1. POThis code appears to achieve the return of a null reference in C++
    primarykey
    data
    text
    <p>My C++ knowledge is somewhat piecemeal. I was reworking some code at work. I changed a function to return a reference to a type. Inside, I look up an object based on an identifier passed in, then return a reference to the object if found. Of course I ran into the issue of what to return if I don't find the object, and in looking around the web, many people claim that returning a "null reference" in C++ is impossible. Based on this advice, I tried the trick of returning a success/fail boolean, and making the object reference an out parameter. However, I ran into the roadblock of needing to initialize the references I would pass as actual parameters, and of course there is no way to do this. I retreated to the usual approach of just returning a pointer.</p> <p>I asked a colleague about it. He uses the following trick quite often, which is accepted by both a recent version of the Sun compiler and by gcc:</p> <pre><code>MyType&amp; someFunc(int id) { // successful case here: // ... // fail case: return *static_cast&lt;MyType*&gt;(0); } // Use: ... MyType&amp; mt = somefunc(myIdNum); if (&amp;mt) // test for "null reference" { // whatever } ... </code></pre> <p>I have been maintaining this code base for a while, but I find that I don't have as much time to look up the small details about the language as I would like. I've been digging through my reference book but the answer to this one eludes me.</p> <p>Now, I had a C++ course a few years ago, and therein we emphasized that in C++ everything is types, so I try to keep that in mind when thinking things through. Deconstructing the expression: "<em>static_cast&lt;MyType</em>&gt;(0);", it indeed seems to me that we take a literal zero, cast it to a pointer to MyType (which makes it a null pointer), and then apply the dereferencing operator in the context of assigning to a reference type (the return type), which should give me a reference to the same object pointed to by the pointer. This sure looks like returning a null reference to me.</p> <p>Any advice in explaining why this works (or why it shouldn't) would be greatly appreciated.</p> <p>Thanks, Chuck</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload