For instance, a program may use a function, strfunc , that returns string objects, and another function, charfunc , that operates on pointers to char, as in the following example.
string strfunc (); void charfunc (const char *);In this situation, it may seem natural to write ‘charfunc (strfunc());’ based on the knowledge that class String has an explicit conversion to char pointers. However, what really happens is akin to
Code like this may run successfully under some other compilers, especially those that delete temporaries relatively late. However, the GNU C++ behavior is also standard-conforming, so if your program depends on late destruction of temporaries it is not portable.
If you think this is surprising, you should be aware that the ANSI C++ committee continues to debate the lifetime-of-temporaries problem.
For now, at least, 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 instance, use the following declaration.
string& tmp = strfunc (); charfunc (tmp);