Thread: the null reference

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708

    Lightbulb the null reference

    I generally avoid working with pointers whenever possible, but of course it can't be totally avoided. so last night I came up with this idea of a class that would make it possible to eliminate the need for them in many situations. I'm hoping you guys can flesh out any bugs but mostly how you'd feel about using something like this. here's an example usage:

    Code:
    #include <iostream>
    #include "null.hpp"
    
    using namespace std;
    using namespace xtd;
    
    class ancestor
    {
          public:
          
          ancestor( string const & name, ancestor const & parent = null )
          : name( name ), parent( parent )
          {      }
    
          string 
                name;
          ancestor const
                & parent;      
    };
    
    void
    print_lineage( ancestor const & my )
    {
          cout << my.name << endl;
          if( my.parent != null )
          {
                cout << my.name << "'s parent: ";
                print_lineage( my.parent );
          }
    }
    
    int
    main( void )
    {
          ancestor
                God( "God" ), 
                Adam( "Adam", God ), 
                Cain( "Cain", Adam );                
          print_lineage( Cain );
    }
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  2. #2
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    No offense, but this is even less than useless. It's completely deranged. It only allows... excuse me, forces a reference to behave similar to how pointers behave. Look at the example function you posted... you've violated the nature of a reference! (The point of a reference isn't just to allow different syntactical sugar.) The idea is, if you get a reference you get to assume that you really have a reference. If you have to check a reference for null, you've not eliminated the need for pointers... you made references into pointers, and at the same time confused everyone.

    Soma

  3. #3
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    >> If you have to check a reference for null, you've not eliminated the need for pointers... you made references into pointers, and at the same time confused everyone.

    yes - if every reference handled had to be checked for null, but that is not what I am advocating here. even with pointers, we generally know exactly when to check for NULL (eg: malloc) and when not to (eg: within an array processing routine). it's all about context.

    >> The point of a reference isn't just to allow different syntactical sugar.

    well, they allow us to write code that is clearer and more uniform. if you prefer to call that sugar then so be it.

    >> No offense, but this is even less than useless. It's completely deranged.

    classic.

    perhaps it's not for everyone, but I encourage you to experiment with it some more before you rule out it's usefulness.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  4. #4
    Use this: dudeomanodude's Avatar
    Join Date
    Jan 2008
    Location
    Hampton, VA
    Posts
    391
    I generally avoid working with pointers whenever possible, but of course it can't be totally avoided.
    Maybe it "could" be totally avoided, but no sane person would tell you that in every class definition you have to use a reference (making it non-copyable) or an actual instance of a class all to avoid the use of pointers.

    I agree, I don't use pointers when I don't have to. But sometimes "I have to." Any time you have to "iterate" a structure, any time you need to decide whether or not to dynamically allocate a new class object, etc., you're going to use pointers (iterators are an example of implicit pointer use).

    I agree that references have certain advantages over pointers in certain situations. So that's why they're there... and I'm not exactly sure what you're trying to accomplish then...

    If people want to litter their code with the over-use of pointers (over-using the this-> is a pet-peeve of mine), so be it. It might be kinda silly to you or me, but the functionality of references already exists, so what are you trying to do? Maybe you can write your own language where everyone will be forced to do things the way you want, and you can name it Java.
    Ubuntu Desktop
    GCC/G++
    Geany (for quick projects)
    Anjuta (for larger things)

  5. #5
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    the code I posted was simply a contrived example. a more typical usage might be:

    Code:
    class database
    {
    	class table
    	{	};
    
    	table &
    	retrieve_table_1( string const & name )
    	{
    	/*
    		if found, return a reference to the table.  
    		otherwise, return null.
    	*/	
    	}
    
    	bool
    	retrieve_table_2( string const & name, table & result )
    	{
    	/*
    		if found, result is valid and return true. 
    		otherwise, return false.
    	*/	
    	}
    
    	table *
    	retrieve_table_3( string const & name )
    	{
    	/*
    		if found, return a pointer to the table. 
    		otherwise, return NULL.
    	*/	
    	}
    
    };
    given the choice, I would choose to use the function retrieve_table_1 because it has a more simple interface. moreover, since it's clear that the table may not exist there wouln't be any confusion about the need to check for a null reference.
    Last edited by Sebastiani; 04-14-2008 at 10:47 PM.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  6. #6
    Use this: dudeomanodude's Avatar
    Join Date
    Jan 2008
    Location
    Hampton, VA
    Posts
    391
    You've lost me. What good does it do whether or not you can check if a reference is null or not if I'm forced to call the function like this:
    Code:
    Table m_table;
    
    table = retrieve_table_1( string const & a_name );
    In which case, it won't even compile without there being something to be referenced.
    Last edited by dudeomanodude; 04-14-2008 at 10:58 PM.
    Ubuntu Desktop
    GCC/G++
    Geany (for quick projects)
    Anjuta (for larger things)

  7. #7
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108

    Thumbs up

    I encourage you to experiment with it some more before you rule out it's usefulness.
    Uh... no. At the very best, the very best, with your "addition" you save one character per reference event over a pointer, and you still subvert reference logic.

    I would choose to use the function retrieve_table_1 because it has a more simple interface.
    O_o

    Nothing involving this would be simple. (If you can write the class so that methods return your "'null'" or a reference then you can write it to return 'null' or a pointer to an instance just as easily--meaning that the user wouldn't have to worry about delete/free/etc. issues.)

    I mean, references can not be reassigned. Suppose, for example, your writing a tool to update CD catalog information for various versions, each version mirroring the old and adding additional information to the tables, of a GUI database utility. Surely, you don't want to query for tables you don't need! You get wonky code because you can't just rely on fall through, nor can you reassign the reference.

    Code:
    table 
          & table = retrieve_table_1( name );
    if( table != null )
    {
          for( unsigned r = 0; r < table.rows( ); r++ )
          {
          /*
                process a row
          */      
          }      
    }
    O_o

    Code:
    table 
          * table = retrieve_table_3( name );
    if( table != null )
    {
          for( unsigned r = 0; r < table->rows( ); r++ )
          {
          /*
                process a row
          */      
          }      
    }
    What have you gained over my example--besides a few less characters? (Keeping in mind that if the method can return a reference the object must manage the 'table's existence.)

    Soma

  8. #8
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    There never has been, nor will there ever be such a thing as a null reference in C++. There is no way of creating such a thing and no way for such a thing to ever exist. Any such attempt to create one is an invalid C++ program.
    The whole idea is itself a bug. What you're thinking of is impossible - end of story - Kapish?!
    In fact I think it would be quite a stretch for one to call themselves a C++ programmer without knowing this.

    Section 8.3.2 paragraph 4:
    "A reference shall be initialized to refer to a valid object or function.
    [Note: in particular, a null reference cannot exist in a well-defined
    program, because the only way to create such a reference would be to bind it
    to the ``object'' obtained by dereferencing a null pointer, which causes
    undefined behavior."
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  9. #9
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    like this:

    Code:
    table 
          & table = retrieve_table_1( name );
    if( table != null )
    {
          for( unsigned r = 0; r < table.rows( ); r++ )
          {
          /*
                process a row
          */      
          }      
    }
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I think Sebastiani wants the kind of pointer-like object references that exist in Java and co.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Banned
    Join Date
    Nov 2007
    Posts
    678
    is this a null reference?
    Code:
    MyClass& func()
    {
        MyClass obj;
        // time pass :D
        return obj;
    }
    void flips()
    {
        MyClass& ref = func(); // null reference?
    }

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    No, it is just undefined behaviour. ref refers to an object that no longer exists.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Banned
    Join Date
    Nov 2007
    Posts
    678
    undefined!!!
    that's the purpose and intent of the OP (at least it was my purpose)
    how do i check that "ref" is a valid or invalid reference?
    we have this convention of NULL pointer being invalid (not a bulletproof way though, but that's C++, and programmers know)
    how we check for above "ref" being valid or invalid?
    i has the same situation in my project, and it is giving me nightmares! >_<

  14. #14
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    I think Sebastiani wants the kind of pointer-like object references that exist in Java and co.
    Then he should program in Java.

    undefined!!!
    that's the purpose and intent of the OP (at least it was my purpose)
    how do i check that "ref" is a valid or invalid reference?
    we have this convention of NULL pointer being invalid (not a bulletproof way though, but that's C++, and programmers know)
    how we check for above "ref" being valid or invalid?
    i has the same situation in my project, and it is giving me nightmares! >_<
    No. Just... no. God, no! No amount of jury rigging will protect you from idiocy. Sorry, but we are discussing C++ not some magic language that disallows all forms of programmer errors. The code, and offering, provided by Sebastiani will not work to check against a null reference because, strangely, as iMalc said, there is no such thing. The only thing that the Sebastiani offering will provide is a check against his offering which would have to be returned specifically--returning it by accident would be an even bigger issue.

    what if i got an object by reference, which was not a local object, which was heap allocated one, but some how, in difficult to follow code, the object is deleted, and all i have is the reference, how to check is it valid?
    This offering, indeed any offering that subverts reference logic, will not help you debug a program. It can't help you find and correct programmer errors. There are however generations of tools that will help you debug a program... use them. (In your case a heavily modified form of new/new[]/delete/delete[]/malloc/realloc/calloc/free/etc. and something very similar to 'assert' would be a huge help.)

    Soma

  15. #15
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by manav View Post
    undefined!!!
    that's the purpose and intent of the OP (at least it was my purpose)
    how do i check that "ref" is a valid or invalid reference?
    we have this convention of NULL pointer being invalid (not a bulletproof way though, but that's C++, and programmers know)
    how we check for above "ref" being valid or invalid?
    i has the same situation in my project, and it is giving me nightmares! >_<
    One way to easily detect that some object has been free/deleted is to create your own versions of new & delete, and let the delete version fill in the memory with some known pattern (e.g. 0xCFCFCFCFCF - that's almost guaranteed to crash you if you use it as a pointer).

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory leaks problem in C -- Help please
    By Amely in forum C Programming
    Replies: 14
    Last Post: 05-21-2008, 11:16 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. . . . . . . - . . . - -
    By The Brain in forum C++ Programming
    Replies: 17
    Last Post: 05-17-2005, 04:01 AM
  4. Replies: 6
    Last Post: 03-02-2005, 02:45 AM
  5. opengl program as win API menu item
    By SAMSAM in forum Game Programming
    Replies: 1
    Last Post: 03-03-2003, 07:48 PM