Checking if a variable is initialized

前端 未结 13 1444
后悔当初
后悔当初 2020-12-28 11:59

Seems like this would be a duplicate, but maybe it is just so obvious it hasn\'t been asked...

Is this the proper way of checking if a variable (not pointer) is init

13条回答
  •  -上瘾入骨i
    2020-12-28 12:22

    With C++-11 or Boost libs you could consider storing the variable using smart pointers. Consider this MVE where toString() behaviour depends on bar being initialized or not:

    #include 
    #include 
    
    class Foo {
    
    private:
        std::shared_ptr bar;
    
    public:
        Foo() {}
        void setBar(int bar) {
            this->bar = std::make_shared(bar);
        }
        std::string toString() const {
            std::ostringstream ss;
            if (bar)           // bar was set
                ss << *bar;
            else               // bar was never set
                ss << "unset";
            return ss.str();
        }
    };
    

    Using this code

    Foo f;
    std::cout << f.toString() << std::endl;
    f.setBar(42);
    std::cout << f.toString() << std::endl;
    

    produces the output

    unset
    42
    

提交回复
热议问题