Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

std

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?

like image 445
bogdan Avatar asked Jul 30 '11 16:07

bogdan


3 Answers

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
}
like image 66
jahhaj Avatar answered Oct 22 '22 16:10

jahhaj


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.

like image 34
Ferruccio Avatar answered Oct 22 '22 15:10

Ferruccio


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.

like image 44
Dennis Zickefoose Avatar answered Oct 22 '22 16:10

Dennis Zickefoose