Re: Strange warning from g++ "returning reference to temporary"
On Dec 5, 3:18 am, irotas <goo...@irotas.net> wrote:
Consider the following code:
struct Foo
{
operator const char* const&() const
{
return s; // <-- "warning: returning reference to temporary"
}
operator char*&()
{
return s; // <-- no warning!
}
char* s;
};
Aside from the "why would you want to do that anyway?" (there is a
reason!), could someone please explain the warning, and why there is
no warning on the non-const version?
Should there be a warning on the non-const version, or is it actually
OK?
Because `const char*' is a pointer to const char, and Foo::s is a
pointer to non-const char: compiler automatically casts pointer to non-
const to const, so here's a temporary. The following is equivalent of
code generated by a typical compiler:
operator const char* const&() const
{
const char *tmp = s;
return tmp;
}
With non-const vesion types already match, so there's no need in
conversion, hence no temporary is created.
You might want to remove reference symbol from operator prototype.
--
Cheers,
Alex
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]