Alex Rivera | Logout

How do I prevent trouble arising from std::string being constructed from `0`?

Asked 2011-06-26T13:53:29.167
19
void foo (const std::string &s) {}

int main() {
  foo(0);   //compiles, but invariably causes runtime error
  return 0;
}

The compiler (g++ 4.4) apparently interprets 0 as char* NULL, and constructs s by calling string::string(const char*, const Allocator &a = Allocator()). Which is of course useless, because the NULL pointer is not a valid pointer to a c-string. This misinterpretation does not arise when I try to call foo(1), this helpfully produces a compile-time error.

Is there any possibility to get such an error or warning at compile-time when I accidentally call a function like

void bar(const std::string &s, int i=1);

with bar(0), forgetting about the string, and actually meaning to have i=0?

Edit
Report

1 Answer

10

This is kind of ugly, but you could create a template that will produce an error when instantiated:

template <typename T>
void bar(T const&)
{
    T::youHaveCalledBarWithSomethingThatIsntAStringYouIdiot();
}

void bar(std::string const& s, int i = 1)
{
    // Normal implementation
}

void bar(char const* s, int i = 1)
{
    bar(std::string(s), i);
}

Then using it:

bar(0); // produces compile time error
bar("Hello, world!"); // fine
answered 2011-06-26T14:10:51.610

Your Answer