Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

c++ - g++ treats returned string literal as const char pointer not const char array

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;
}

produces the result:

Template const char array constructor
char* constructor

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*'"

Even more surprisingly if you remove the char* constructor then the code doesn't compile with g++.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...