相关疑难解决方法(0)

临时的一生

以下代码工作正常,但为什么这是正确的代码?为什么foo()返回的临时的"c_str()"指针有效?我想,当输入bar()时,这个临时性已经被破坏了 - 但它似乎不是这样的.那么,现在我假设foo()返回的临时值将在调用bar()之后被销毁 - 这是正确的吗?为什么?

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

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

bar( foo().c_str() );
Run Code Online (Sandbox Code Playgroud)

c++ temporary c++-faq lifetime full-expression

37
推荐指数
2
解决办法
3149
查看次数

标签 统计

c++ ×1

c++-faq ×1

full-expression ×1

lifetime ×1

temporary ×1