From 82ba818ff456bcd6d56a06226e3f27e98fbb55c3 Mon Sep 17 00:00:00 2001 From: Craig Jennings Date: Thu, 14 Aug 2025 22:58:58 -0500 Subject: removing all downloaded devdocs files --- devdocs/gcc~13/temporaries.html | 20 -------------------- 1 file changed, 20 deletions(-) delete mode 100644 devdocs/gcc~13/temporaries.html (limited to 'devdocs/gcc~13/temporaries.html') diff --git a/devdocs/gcc~13/temporaries.html b/devdocs/gcc~13/temporaries.html deleted file mode 100644 index f933a394..00000000 --- a/devdocs/gcc~13/temporaries.html +++ /dev/null @@ -1,20 +0,0 @@ -

14.7.3 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:

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

- © Free Software Foundation
Licensed under the GNU Free Documentation License, Version 1.3.
- https://gcc.gnu.org/onlinedocs/gcc-13.1.0/gcc/Temporaries.html -

-
-- cgit v1.2.3