g ++将返回的字符串文字作为const char指针,而不是const char数组 [英] g++ treats returned string literal as const char pointer not const char array
问题描述
我看到一些奇怪的行为,当从一个函数返回一个字符串字面量应该执行使用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\n");
}
Test(char* foo)
{
printf("char* constructor\n");
}
};
Test fn()
{
return "foo";
}
int main()
{
Test t("bar");
Test u = fn();
return 0;
}
产生结果:
Template const char array constructor
char* constructor
on 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?
推荐答案
看起来这是一个bug,影响几个版本的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
这篇关于g ++将返回的字符串文字作为const char指针,而不是const char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!