gcc: Temporaries
1
1 13.7.3 Temporaries May Vanish Before You Expect
1 -----------------------------------------------
1
1 It is dangerous to use pointers or references to _portions_ of a
1 temporary object. The compiler may very well delete the object before
1 you expect it to, leaving a pointer to garbage. The most common place
1 where this problem crops up is in classes like string classes,
1 especially ones that define a conversion function to type 'char *' or
1 'const char *'--which is one reason why the standard 'string' class
1 requires you to call the 'c_str' member function. However, any class
1 that returns a pointer to some internal structure is potentially subject
1 to this problem.
1
1 For example, a program may use a function 'strfunc' that returns
1 'string' objects, and another function 'charfunc' that operates on
1 pointers to 'char':
1
1 string strfunc ();
1 void charfunc (const char *);
1
1 void
1 f ()
1 {
1 const char *p = strfunc().c_str();
1 ...
1 charfunc (p);
1 ...
1 charfunc (p);
1 }
1
1 In this situation, it may seem reasonable to save a pointer to the C
1 string returned by the 'c_str' member function and use that rather than
1 call 'c_str' repeatedly. However, the temporary string created by the
1 call to 'strfunc' is destroyed after 'p' is initialized, at which point
1 'p' is left pointing to freed memory.
1
1 Code like this may run successfully under some other compilers,
1 particularly obsolete cfront-based compilers that delete temporaries
1 along with normal local variables. However, the GNU C++ behavior is
1 standard-conforming, so if your program depends on late destruction of
1 temporaries it is not portable.
1
1 The safe way to write such code is to give the temporary a name, which
1 forces it to remain until the end of the scope of the name. For
1 example:
1
1 const string& tmp = strfunc ();
1 charfunc (tmp.c_str ());
1