From 754bbf7a25a8dda49b5d08ef0d0443bbf5af0e36 Mon Sep 17 00:00:00 2001 From: Craig Jennings Date: Sun, 7 Apr 2024 13:41:34 -0500 Subject: new repository --- devdocs/gcc~13/temporaries.html | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create 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 new file mode 100644 index 00000000..f933a394 --- /dev/null +++ b/devdocs/gcc~13/temporaries.html @@ -0,0 +1,20 @@ +

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