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
?
std::string is just fine with '\0' byte in the string, no need to use std::vector just because of it.
There is no functionality difference between string and std::string because they're the same type.
'\0' is the null termination character.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With