dimanche 6 septembre 2020

Object lifetime of std::stirng returning const char* as a return value

In C++11:

#include <string>
#include <iostream>

const char*Inner() {
  std::string content;
  content = "const characters are returned.";
  return content.c_str();
}

const char* Outer() {
  return Inner();
}
int main(){
  std::cout << "result " << Outer() <<"\n"; // <- Spot 1
  return 0;
}

I am kind of understand the explanation in const char* Return Type. The string object is destroyed when the stack is gone. But I think that should happen when the Spot 1 completed execution. After that, the Inner stack is popped? But in this case, the Spot 1 is still executing but the stacks are destroyed. Could anyone explain when the stack gets destroyed?

Another question related the context is: if I change the function to

const char*Inner() {
  std::string content;
  content = "const characters are returned.";
  const char* ptr = content.c_str()
  return ptr;
}

In this case, The string content is destroyed. Is that because the return is a pointer, so the value of the pointer(address) is returned but the content the pointer pointed to is recycled?

Aucun commentaire:

Enregistrer un commentaire