g++ 将返回的字符串文字视为 const char 指针而不是 const char 数组
当从一个应该使用 g++(版本 4.7.3)执行隐式转换的函数返回字符串文字时,我看到了一些奇怪的行为.谁能解释为什么下面的代码:
I'm seeing some odd behaviour when returning a string literal from a function that should perform an implicit conversion with g++ (version 4.7.3). Can anyone explain why the following code:
#include <stdio.h>
class Test
{
public:
template <unsigned int N>
Test(const char (&foo)[N])
{
printf("Template const char array constructor
");
}
Test(char* foo)
{
printf("char* constructor
");
}
};
Test fn()
{
return "foo";
}
int main()
{
Test t("bar");
Test u = fn();
return 0;
}
产生结果:
Template const char array constructor
char* constructor
在 g++ 上?令人惊讶的是,在从 fn() 生成返回值时,优先选择 char* 构造函数而不是 const char 数组构造函数.诚然,有一个警告,不推荐使用从字符串常量到 'char*' 的转换"
on g++? The surprising thing being that the char* constructor is chosen in preference to the const char array constructor when generating the return value from fn(). Admittedly there is a warning, "deprecated conversion from string constant to 'char*'"
更令人惊讶的是,如果您删除 char* 构造函数,那么代码将无法使用 g++ 编译.
Even more surprisingly if you remove the char* constructor then the code doesn't compile with g++.
它在 clang 中按预期工作(两次都使用模板构造函数),这让我认为这是一个编译器错误,但也许它只是 C++ 规范的一个奇怪的角落 - 有人可以确认吗?
It works as expected with clang (Template constructor used both times), which makes me think this is a compiler bug, but maybe it's just a weird corner of the C++ spec - could anyone confirm?
推荐答案
看来这是一个影响多个版本的 gcc 的错误,已被反复报告,最近一次是大约一个月前针对最新版本,4.8.2.请参阅 http://gcc.gnu.org/bugzilla/show_bug.cgi?id=24666
It appears that this is a bug affecting several versions of gcc which has been reported over and over again, most recently about a month ago against the most recent version, 4.8.2. See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=24666
相关文章