9

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 crashing?

bogdan
  • 9,056
  • 10
  • 37
  • 42
  • What are you doing with str inside foo ? If you test for if str is NULL and gracefully exit from the function, it shouldn't crash. – arunkumar Jul 30 '11 at 16:02
  • You have been given some helpful suggestions, but are you sure you are approaching this right? Why are you using a pointer? Part of the beauty of std::string (and references) is that you don't have to mess with the pointer. (Usually) – John Jul 30 '11 at 16:15
  • This is also the reason for the infamous `std::string s(false)` thing. – Seth Carnegie Jul 30 '11 at 16:53
  • 3
    "Doctor, doctor, it hurts when I do this!" ;-) – Steve Jessop Jul 30 '11 at 17:32

3 Answers3

12

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
}
jahhaj
  • 763
  • 4
  • 9
8

You could use 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
    }
}

To call it with a string:

string s;
func(optional<string>(s));

and without a string:

func(optional<string>());

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

Ferruccio
  • 98,941
  • 38
  • 226
  • 299
  • 3
    optional now exists in C++17 as [std::optional](http://en.cppreference.com/w/cpp/utility/optional). – Zitrax Dec 07 '16 at 09:49
1

You have a function that accepts a std::string, so provide it an std::string, not a pointer.

foo(std::string());

This will provide the function with an empty string, which is probably what you would have interpreted your null value as anyhow.

Dennis Zickefoose
  • 10,791
  • 3
  • 29
  • 38