简体   繁体   中英

Does creating a std::string in a function and returning it create a memory leak?

Is calling this function creating a memory leak?

#include <iostream>

std::string somefunc()
{
  std::string somestrng;
  somestrng = "Fred";
  return somestrng;
}

int main()
{
    std::cout << "Hello World!\n";
    std::string receiver = somefunc();
    std::cout << "-->" << receiver.data() << "<--" << std::endl;
}

I've read about "value semantics" but I can't envision it.

No, there is no memory leak in the shown program.

In general, memory leaks happen when you allocate dynamic memory, and neglect to deallocate that memory.

You don't directly allocate any dynamic memory in the example program. std::string may potentially allocate some dynamic memory, but it will also deallocate it. For future learning, I would recommend studying the RAII pattern, which the string class follows.

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