In this code:
char tempArray[30];
tempArray is a variable with automatic storage time. When tempArray "falls out of scope", it is automatically destroyed. You copy the contents of this array (somewhat awkwardly) to std::string , and then return the string value by value. Then tempArray destroyed. It is important to note that tempArray is an array . This is not a pointer to the first element of the array (as a rule, it is perceived incorrectly), but the array itself. Since tempArray destroyed, the array is destroyed.
A leak would occur if you used a variable with dynamic storage duration, for example:
char* tempArray = new char[30]; strcpy(tempArray, "This is a test"); return string(tempArray);
Note new[] without matching delete[] . Here tempArray is still a variable with automatic storage time, but this time it is a pointer, and what it indicates has a dynamic storage duration. In other words, tempArray destroyed when it goes out of scope, but it's just a pointer. What it points to is an array of char is not destroyed because you do not delete[] it.
source share