On 2008-11-18 10:52:48 -0500, Andy Gibbs <andyg1...@hotmail.co.uksaid:The problem comes in the line "Function(&Test("test2"));"
with the warning "taking address of temporary". I am using
GCC 4.1.2. However, the code runs as expected with the
following output:
test1:
ctor
str=test1
dtor
test2:
ctor
str=test2
dtor
test3
null
The code above demonstrates that the Test object is not
destroyed until after Function is called, so I cannot see
why the compiler complains about this.
The compiler warns about it because the code takes the addressHas this changed in the latest draft. According to my copy of
of a temporary, although there's nothing inherently wrong with
doing that.
the standard (version 1998---out of date, I know), "The
operand [of the unary & operator] shall be an lvalue or a
qualified-id". His expression was &Test("test2"); IMHO, the
compiler generated a warning because it was being laxist.
If I compile his code with Sun CC, I get:
"addrtemp.cc", line 34: Warning, badargtypel2w: String literal
converted to char* in formal argument str in call to Test::Test
(char*).
"addrtemp.cc", line 37: Warning, badargtypel2w: String literal
converted to char* in formal argument str in call to Test::Test
(char*).
"addrtemp.cc", line 37: Error, wantvarname: The "&" operator can
only be applied to a variable or other l-value.
Which is what I'd expect from a good compiler. Curiously
enough, g++ only generates says:
addrtemp.cc: In function 'int main(int, char**)':
addrtemp.cc:37: warning: taking address of temporary
even with -std=c++98 -pedantic (I'd call this a bug), and VC++
doesn't say anything.
If you misuse the result you can get in trouble. ApparentlyApparently, the writers of his compiler don't care about the
the writers of your compiler thnk that you can't be trusted to
use that address without screwing up.
standard. (Nothing new there.) And it's the members of the
stadnards committee who think you can't be trusted. (Or just
wanted to remain compatible with C in this respect.)
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34