g++ treats returned string literal as const char pointer not const char array(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
这篇关于g++ 将返回的字符串文字视为 const char 指针而不是 const char 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:g++ 将返回的字符串文字视为 const char 指针而不是


基础教程推荐
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 设计字符串本地化的最佳方法 2022-01-01