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

前端 未结 3 1342
臣服心动
臣服心动 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:52

    std::string has a constructor that takes a const char* parameter. That's constructor is going to crash when you pass NULL to it, and that constructor is called implicitly when you write foo(NULL).

    The only solution I can think of is to overload foo

    void foo(const std::string& str)
    {
      // your function
    }
    
    void foo(const char* cstr)
    {
      if (cstr == NULL)
        // do something
      else
         foo(std::string(cstr)); // call regular funciton
    }
    

提交回复
热议问题