如何防止从'0`构造std :: string引起的麻烦?

lef*_*out 19 c++ string g++ null-pointer

void foo (const std::string &s) {}

int main() {
  foo(0);   //compiles, but invariably causes runtime error
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译器(g ++ 4.4)显然通过调用来解释0char* NULL和构造.这当然没用,因为指针不是指向c-string的有效指针.当我尝试调用时,这种误解不会出现,这有助于产生编译时错误.sstring::string(const char*, const Allocator &a = Allocator())NULLfoo(1)

当我不小心调用类似的函数时,是否有可能在编译时得到这样的错误或警告

void bar(const std::string &s, int i=1);
Run Code Online (Sandbox Code Playgroud)

bar(0),忘记了string,实际上有意义i=0

Pet*_*der 10

这有点难看,但您可以创建一个在实例化时会产生错误的模板:

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);
}
Run Code Online (Sandbox Code Playgroud)

然后使用它:

bar(0); // produces compile time error
bar("Hello, world!"); // fine
Run Code Online (Sandbox Code Playgroud)

  • +1,即使这种方法失败,如果`T`实际上有一个名为`youHaveCalledBarWithSomethingThatIsntAStringYouIdiot`的公共静态方法,并且不带参数;) (5认同)