g++ 将返回的字符串文字视为 const char 指针而不是 const char 数组

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)