如何允许std:string参数为NULL?

bog*_*dan 8 c++ std

我有一个功能foo(const std::string& str);,如果你使用它,它会崩溃foo(NULL).

我该怎么做才能防止它崩溃?

jah*_*haj 11

std :: string有一个构造函数,它接受一个const char*参数.当你向它传递NULL时,构造函数会崩溃,并且当你编写foo(NULL)时会隐式调用该构造函数.

我能想到的唯一解决方案是重载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
}
Run Code Online (Sandbox Code Playgroud)


Fer*_*cio 8

你可以使用Boost.Optional.

#include <boost/optional.hpp>
#include <string>

using namespace std;
using namespace boost;

void func(optional<string>& s) {
    if (s) {  // implicitly converts to bool
        // string passed in
        cout << *s << endl; // use * to get to the string
    } else {
        // no string passed in
    }
}
Run Code Online (Sandbox Code Playgroud)

用字符串调用它:

string s;
func(optional<string>(s));
Run Code Online (Sandbox Code Playgroud)

没有字符串:

func(optional<string>());
Run Code Online (Sandbox Code Playgroud)

Boost.Optional为您提供了一种类型安全的方法来获取可空值,而无需求助于指针及其相关问题.

  • 现在在C++ 17中作为[std :: optional](http://en.cppreference.com/w/cpp/utility/optional)存在. (3认同)