当我从一个函数中返回一个字符串字面值并希望使用g++(版本4.7.3)执行隐式转换时,我发现一些奇怪的行为。有人能解释一下以下代码的原因吗:
#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
对于g++编译器,这里需要翻译的是令人惊奇的事情是,在从fn()生成返回值时,char*构造函数比const char数组构造函数更受青睐。尽管有一个警告:“从字符串常量到'char *'的转换已被弃用”。
更令人惊讶的是,如果删除char*构造函数,则代码在g++下无法编译。
使用clang工作正常(两次都使用模板构造函数),这使我认为这是编译器错误,但也可能是C ++规范的奇怪角落-是否有人可以证实?
char*
之外,它与其他数组的行为方式相同:const char foo[4] = {}; return foo;
会出现错误:"error: could not convert ‘(const char*)(& foo)’ from ‘const char*’ to ‘Test’"。 - user743382return { "foo" }
。(@hvd 你是对的) - gwiazdorrrprintf
? - Ed Heal