The Lifetime of Objects in foo() and bar()
In C , objects created during function calls are considered temporary objects. Understanding their lifetime is crucial for ensuring correct program behavior.
Consider the following code:
std::string foo() { std::string out = something...; return out; } void bar( const char* ccp ) { // do something with the string.. } bar( foo().c_str() );
Question:
Why is the c_str() pointer of the temporary object returned by foo() valid in the bar() function even after foo() has completed?
Answer:
According to the C standard, a temporary object is destroyed once the full expression that contains its creation is completed. In this case, the full expression is:
bar( foo().c_str() );
In ASCII art, the lifetime of the temporary object looks like this:
____________________ full-expression ranges from 'b' to last ')' bar( foo().c_str() ); ^^^^^ ^ | | birth funeral
The temporary object is created when foo() is called (birth) and destroyed after the expression finishes executing (funeral), ensuring that the c_str() pointer remains valid throughout the execution of bar().
The above is the detailed content of Why is the `c_str()` pointer of a temporary string object valid in `bar()` after its creating function `foo()` has returned?. For more information, please follow other related articles on the PHP Chinese website!