void foo (const std::string &s) {}
int main() {
foo(0); //compiles, but invariably causes runtime error
return 0;
}
编译器(克++ 4.4)显然解释0
如char* NULL
,并通过调用string::string(const char*, const Allocator &a = Allocator())
构建s
。这当然是无用的,因为NULL
指针不是指向c字符串的有效指针。当我尝试呼叫foo(1)
时,这种错误解释不会产生,这有助于产生编译时错误。如何避免由'0'构造std :: string引起的麻烦?
是否有可能得到这样的错误或警告在编译的时候,我不小心调用诸如
void bar(const std::string &s, int i=1);
功能与bar(0)
,忘掉了string
,实际上意味着有i=0
?
不是没有编译器的帮助。一些实现已经添加了一个私有'basic_string(int)'来捕获这种情况。如果不是的话,我想你的运气不好。 –
我很惊讶,这通过海湾合作委员会,它的丑陋的错误/警告,但我会在这里预期的东西。你有没有提高警告水平? –
@Matthieu我找不到任何可以给我警告的选项,但我并没有真正进入gcc警告选项。无论如何,-W-Wall -Wpointer-arith -Wcast-qual'并没有诀窍。 – leftaroundabout