Home > Software engineering >  Does creating a std::string in a function and returning it create a memory leak?
Does creating a std::string in a function and returning it create a memory leak?

Time:12-17

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.

CodePudding user response:

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.

  • Related