c++ - visual studio 中涉及 void*、string 和 const char[] 的意外重载解析

标签 c++

我在 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/

相关文章:

c++ - 标准库中的类型可以过度对齐吗?

c# - 编译一个dlib的.dll文件

c++ - glfwCreateWindow 返回 NULL

c++ - 如何使用模板参数对函数指针进行类型定义

c++ - boost::program_options - 解析多个命令行参数,其中一些是字符串,包括空格和字符

c++ - 字符数组是唯一具有某种形式的空终止的类型吗?

c++ - C++ 中全局对象销毁和 atexit 之间的顺序

c++ - 在 C++ 中查找 vector 中的字符串

c++ - 如何在 C++ 中计算 10 位小数精度的 double 变量

c++ - 在 OpenCV 中计算协方差