Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

c++ - Lifetime of temporaries

The following code works fine, but why is this correct code? Why is the "c_str()" pointer of the temporary returned by foo() valid? I thought, that this temporary is already destroyed when bar() is entered - but it doesn't seem to be like this. So, now I assume that the temporary returned by foo() will be destroyed after the call to bar() - is this correct? And why?

std::string foo() {
  std::string out = something...;
  return out;
}

void bar( const char* ccp ) {
  // do something with the string..
}

bar( foo().c_str() );
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A temporary object is destroyed when the full-expression that lexically contains the rvalue whose evaluation created that temporary object is completely evaluated. Let me demonstrate with ASCII art:

____________________   full-expression ranges from 'b' to last ')'
bar( foo().c_str() );
     ^^^^^          ^
       |            |
     birth       funeral

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...