How to allow a std:string parameter to be NULL?

前端 未结 3 1318
臣服心动
臣服心动 2021-01-17 22:21

I have a function foo(const std::string& str); that it does crash if you call it using foo(NULL).

What can I do to prevent it from cras

3条回答
  •  臣服心动
    2021-01-17 22:40

    You could use Boost.Optional.

    #include 
    #include 
    
    using namespace std;
    using namespace boost;
    
    void func(optional& s) {
        if (s) {  // implicitly converts to bool
            // string passed in
            cout << *s << endl; // use * to get to the string
        } else {
            // no string passed in
        }
    }
    

    To call it with a string:

    string s;
    func(optional(s));
    

    and without a string:

    func(optional());
    

    Boost.Optional gives you a typesafe way to have nullable values without resorting to pointers and their associated problems.

提交回复
热议问题