Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 717
leftaroundabout Avatar asked Jun 26 '11 13:06

leftaroundabout


People also ask

Does std::string have\ 0?

std::string is just fine with '\0' byte in the string, no need to use std::vector just because of it.

What is the difference between a C++ string and an std::string?

There is no functionality difference between string and std::string because they're the same type.

How do you end a string in C++?

'\0' is the null termination character.

Where is std::string defined?

std::string is a typedef for a particular instantiation of the std::basic_string template class. Its definition is found in the <string> header: using string = std::basic_string<char>; Thus string provides basic_string functionality for strings having elements of type char.


1 Answers

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
like image 61
Peter Alexander Avatar answered Oct 24 '22 20:10

Peter Alexander