我在 visual studio 编译器(在 VS2010 和 VS2012 中测试)中遇到了以下意外的重载解析行为。
最小的例子:
#include <iostream>
#include <string>
void f(void *)
{
std::cout << "f(void*)\n";
}
void f(const std::string &)
{
std::cout << "f(const std::string &)\n";
}
int main()
{
f("Hello World!");
}
输出:
> f(void *)
预期输出:
> f(const std::string &)
用 GCC 编译(用 4.6.3 测试)生成预期的输出。
如果我注释掉 f() 的“const std::string &”版本,visual studio 会在没有任何警告的情况下愉快地在/W4 上编译,而 GCC 会发出以下错误(如预期的那样):“来自 'const void 的无效转换*' 到 'void*' [-fpermissive]”。
有谁知道为什么 visual studio 会以这种方式运行,基本上选择 const 强制转换重载而不是将 char[] 转换为 std::string?
有没有办法禁止这种行为,或者至少让 VS 产生一个警告?
最佳答案
对于 VS 2013 Microsoft documents silently dropping const
for string literals作为 C++ 的 Microsoft 特定行为:
Microsoft Specific
In Visual C++ you can use a string literal to initialize a pointer to non-const char or wchar_t. This is allowed in C code, but is deprecated in C++98 and removed in C++11.
...
You can cause the compiler to emit an error when a string literal is converted to a non_const character when you set the
/Zc:strictStrings
(Disable string literal type conversion) compiler option.
对于 VS 2013 之前的版本(例如 VS 2012's documentation),Microsoft 将 C++ 中的字符串文字记录为使用 char
的非常量数组的 C 约定。
关于c++ - visual studio 中涉及 void*、string 和 const char[] 的意外重载解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22192789/