3

I want to know if this causes a memory leak:

std::string test() {
    return *(new std::string(""));
}
Christian Rau
  • 45,360
  • 10
  • 108
  • 185
Zaffy
  • 16,801
  • 8
  • 50
  • 77

2 Answers2

12

Yes, it's a memory leak. When the function returns, a copy is made of the original string object.

Then the original new'ed pointer falls out of scope and is lost - a leak.

Mysticial
  • 464,885
  • 45
  • 335
  • 332
0

To make it less leaking make it return a reference:

std::string& test() {
   return *(new std::string(""));
}
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • 1
    so when I for example have std::string& abc = test(); and I call delete &abc; There won't be any leak ? – Zaffy Dec 02 '11 at 17:21