-2

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.

user2171796
  • 397
  • 2
  • 16
  • 2
    Handy reading: [What is meant by Resource Acquisition is Initialization (RAII)?](https://stackoverflow.com/q/2321511/4581301) – user4581301 Dec 15 '22 at 21:04
  • More useful reading: https://en.cppreference.com/w/cpp/language/raii – user4581301 Dec 15 '22 at 21:04
  • 3
    why do you think this could cause a memory leak? – 463035818_is_not_an_ai Dec 15 '22 at 21:05
  • 2
    The answer is no, by the way, `std::string` follows RAII religiously and manages all of the clean up in every non-program-crashing case that I know of, and if the program crashes you've got bigger problems. – user4581301 Dec 15 '22 at 21:06
  • 1
    TL;DR; No. Unoptimized version would create a string, copy or move it it on return, and destroy the original. An optimized version would use copy elision (return value optimization). – Sergey Kalinichenko Dec 15 '22 at 21:08
  • @OP -- Let's ask you -- How would you have cleaned up the memory leak if you believed there was one occuring? You can't use `delete`, since there is no `new` involved in the code. – PaulMcKenzie Dec 15 '22 at 21:08
  • *I've read about "value semantics" but I can't envision it.* -- Learn about implementing copy constructor, assignment operator, and destructor for classes that manage resources (such as memory). Then you will see how all of this works properly. – PaulMcKenzie Dec 15 '22 at 21:11
  • 2
    Always good to read up on the ["Rule of three"](https://en.cppreference.com/w/cpp/language/rule_of_three). – G.M. Dec 15 '22 at 21:14
  • @PaulMcKenzie If I could provide objective evidence of a memory leak in such code, I'd be submitting a bug report to the vendor of the compiler and standard library. – Peter Dec 15 '22 at 23:18
  • Thank you all. I understand better now. The comment that helped me the most was: . . . . TL;DR; No. Unoptimized version would create a string, copy or move it it on return, and destroy the original. An optimized version would use copy elision (return value optimization). – Sergey Kalinichenko – user2171796 Dec 16 '22 at 16:26

1 Answers1

1

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326