Return a “NULL” object if search result not found

前端 未结 8 2119
一个人的身影
一个人的身影 2020-11-28 02:23

I\'m pretty new to C++ so I tend to design with a lot of Java-isms while I\'m learning. Anyway, in Java, if I had class with a \'search\' method that would return an object

相关标签:
8条回答
  • 2020-11-28 03:24

    You can easily create a static object that represents a NULL return.

    class Attr;
    extern Attr AttrNull;
    
    class Node { 
    .... 
    
    Attr& getAttribute(const string& attribute_name) const { 
       //search collection 
       //if found at i 
            return attributes[i]; 
       //if not found 
            return AttrNull; 
    } 
    
    bool IsNull(const Attr& test) const {
        return &test == &AttrNull;
    }
    
     private: 
       vector<Attr> attributes; 
    };
    

    And somewhere in a source file:

    static Attr AttrNull;
    
    0 讨论(0)
  • 2020-11-28 03:26

    In C++, references can't be null. If you want to optionally return null if nothing is found, you need to return a pointer, not a reference:

    Attr *getAttribute(const string& attribute_name) const {
       //search collection
       //if found at i
            return &attributes[i];
       //if not found
            return nullptr;
    }
    

    Otherwise, if you insist on returning by reference, then you should throw an exception if the attribute isn't found.

    (By the way, I'm a little worried about your method being const and returning a non-const attribute. For philosophical reasons, I'd suggest returning const Attr *. If you also may want to modify this attribute, you can overload with a non-const method returning a non-const attribute as well.)

    0 讨论(0)
提交回复
热议问题