简体   繁体   中英

Am I responsible for freeing/deleting a string returned by stringstream.str()

Am I responsible for deleting a returned std::string created by a stringstream? As in the following code:

std::string MyClass::getReturnMessage() {
    std::stringstream msg;
    msg << "Test return code string stream!";
    return msg.str();
}

void MyClass::callerMethod() {
    std::string msg = getReturnMessage();
    // do I need to call delete msg?
}

If I'm not responsible for calling delete on the returned value, why not? What is the memory management model here that requires or doesn't require me to call delete?

Only call delete on objects you have allocated with new .

Since there's no new in your case, don't call delete either.

The reason is that the returned std::string has automatic storage duration (since it's allocated on the stack), so it will automatically get destroyed when it goes out of scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM