Node: Temporaries, Next: , Previous: Static Definitions, Up: C++ Misunderstandings



Temporaries May Vanish Before You Expect

It is dangerous to use pointers or references to portions of a temporary object. The compiler may very well delete the object before you expect it to, leaving a pointer to garbage. The most common place where this problem crops up is in classes like string classes, especially ones that define a conversion function to type char * or const char *--which is one reason why the standard string class requires you to call the c_str member function. However, any class that returns a pointer to some internal structure is potentially subject to this problem.

For example, a program may use a function strfunc that returns string objects, and another function charfunc that operates on pointers to char:

     string strfunc ();
     void charfunc (const char *);
     
     void
     f ()
     {
       const char *p = strfunc().c_str();
       ...
       charfunc (p);
       ...
       charfunc (p);
     }
     

In this situation, it may seem reasonable to save a pointer to the C string returned by the c_str member function and use that rather than call c_str repeatedly. However, the temporary string created by the call to strfunc is destroyed after p is initialized, at which point p is left pointing to freed memory.

Code like this may run successfully under some other compilers, particularly obsolete cfront-based compilers that delete temporaries along with normal local variables. However, the GNU C++ behavior is standard-conforming, so if your program depends on late destruction of temporaries it is not portable.

The safe way to write such code is to give the temporary a name, which forces it to remain until the end of the scope of the name. For example:

     string& tmp = strfunc ();
     charfunc (tmp.c_str ());