Returning a “NULL reference” in C++?

前端 未结 8 554
旧巷少年郎
旧巷少年郎 2020-12-05 00:02

In dynamically typed languages like JavaScript or PHP, I often do functions such as:

function getSomething(name) {
    if (content_[name]) return content_[na         


        
相关标签:
8条回答
  • 2020-12-05 00:27

    Why "besides using pointers"? Using pointers is the way you do it in C++. Unless you define some "optional" type which has something like the isNull() function you mentioned. (or use an existing one, like boost::optional)

    References are designed, and guaranteed, to never be null. Asking "so how do I make them null" is nonsensical. You use pointers when you need a "nullable reference".

    0 讨论(0)
  • 2020-12-05 00:29

    Here are a couple of ideas:

    Alternative 1:

    class Nullable
    {
    private:
        bool m_bIsNull;
    
    protected:
        Nullable(bool bIsNull) : m_bIsNull(bIsNull) {}
        void setNull(bool bIsNull) { m_bIsNull = bIsNull; }
    
    public:
        bool isNull();
    };
    
    class SomeResource : public Nullable
    {
    public:
        SomeResource() : Nullable(true) {}
        SomeResource(...) : Nullable(false) { ... }
    
        ...
    };
    

    Alternative 2:

    template<class T>
    struct Nullable<T>
    {
        Nullable(const T& value_) : value(value_), isNull(false) {}
        Nullable() : isNull(true) {}
    
        T value;
        bool isNull;
    };
    
    0 讨论(0)
提交回复
热议问题