In the above, (if I understand correctly), the call "return_string().c_str()" creates enough space on the stack, to store the returned string "test". However, I am confused, as to how is the space deallocated, as there is no variable holding the reference to the newly-dynamically-allocated-space-on-stack (which in turn means that there would be no automatic deallocation of stack-memory).
Would above code leak memory?
I am sorry if I am sounding idiotic, but I will be highly grateful if I could be cleared of my doubts.
As any value-returning function, return_string() creates a nameless temporary object, whose lifetime ends at the end of full expression (in this case, the full expression is "strcmp(return_string().c_str(), "test") == 0"). .c_str() is also a value-returning function, it creates a temporary pointer that points at the first character in the temporary string returned by return_string().
strcmp() receives that pointer, and follows it to examine the contents of the string (which is still fine, since the full expression didn't yet end). It is also a value-returning function and it returns a nameless int.
At the end of full expression (after ==0), the destructors for all temporaries are run in the order opposite of their construction: the int and the pointer are non-class types, so nothing needs to be done, but the string has a destructor, so it is executed.