C++ string that can be NULL

2019-03-27 17:07发布

I'm used to passing around string like this in my C++ applications:

void foo(const std::string& input)
{
  std::cout << input.size() << std::endl;
}

void bar()
{
  foo("stackoverflow");
}

Now I have a case where I want the string to be NULL:

void baz()
{
  foo("stackoverflow");
  foo(NULL); // very bad with foo implementation above
}

I could change foo to:

void foo(const std::string* input)
{
  // TODO: support NULL input
  std::cout << input->size() << std::endl;
}

But to pass a string literal or copy a char* to that implementation of foo I need to write something like this:

void bar()
{
  string input("hi"); // annoying temporary
  foo(&input);
  foo(NULL);  // will work as long as foo handles NULL properly
}

I started thinking about inheriting from std::string and adding a null property, but I'm not so sure it's a good idea. Maybe it is better to simply use a const char* string for parameters that can be NULL, but what if I want to save a copy of the string (or NULL) without having to manage its memory myself? (See What are some of the drawbacks to using C-style strings? etc.)

Any clever solution around?

标签: c++ string null
7条回答
2楼-- · 2019-03-27 17:51

Why don't you overload the function and give the second overload no argument? Then both overloads can internally call a function that provides the read logic and that, itself, gets passed a pointer to std::string.

void foo_impl(string const* pstr) { … }

void foo(string const& str) {
    foo_impl(&str);
}

void foo() {
    foo_impl(0);
}
查看更多
登录 后发表回答