James Hatton
James Hatton

Reputation: 696

Deleting pointer before returning value from function

If I have this:

double foo()
{
double* ptr = new double(0);

return *ptr;
}

If ptr is not deleted before returning, this will cause a memory leak? Therefore, what is the correct way to delete ptr before returning from the function?

Upvotes: 0

Views: 1046

Answers (5)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272517

If you don't want the object (as opposed to its value) to exist beyond the scope of the function, then it doesn't make much sense to dynamically-allocate it.

Just allocate it on the stack:

double foo() {
    double d = 0;

    ...

    return d;
}

The alternative is to let the object exist beyond the scope of the function, in which case you don't want to delete it before returning. The best way to manage this is with some kind of smart pointer (this handles memory management automatically in most cases).

Upvotes: 4

James Kanze
James Kanze

Reputation: 153919

Why are you allocating a double dynamically? I can't think of any context where new double would make sense. Just declare the double as a local variable.

About the only time you'd want to allocate an object dyamically whose lifetime ends at the end of the function would be if polymorphism is involved. In those cases, you can use std::auto_ptr (or std::unique_ptr if you're sure that all of the compilers you will ever see will support C++11).

Upvotes: 0

Silviu
Silviu

Reputation: 835

It's OK as long as you receive the return value of foo() in a pointer in the same class you are calling the function from. Afterwards you can use delete on that pointer when you don't need it anymore...

Upvotes: 0

escargot agile
escargot agile

Reputation: 22379

If you're returning the value pointed by ptr then you definitely do not want to delete it before leaving the function. If you delete it and then return it, the calling function will try to access memory that has been freed, and this is forbidden.

Upvotes: 0

user1202136
user1202136

Reputation: 11567

You have several solutions:

  • scoped_ptr
  • declaring a variable on the stack

Upvotes: 7

Related Questions