1

If I implement this code, is it producing a memory leak? If it is not a memory leak, when will the memory be deleted?

class MyClass 
{
  public:
    void foo() {
      static MyClass *element = new MyClass(); 
    }
};
1
  • 2
    It will be deleted when you call a delete on it. I don't see the point of doing this since it's a static variable anyway. Technically if you never call delete it is a memory leak, but it's pretty much the same as a simple static variable, so it's not really a leak. (as long as you keep pointing to this heap object) Commented Sep 10, 2015 at 14:10

1 Answer 1

5

Well, a little of both.

Yes; there is no code that deletes it (the associated delete element).

No; there will only be a single instance of it and the OS will reclaim the memory when the process exits anyway. The memory usage will not grow unbounded.

Taking into account possible future maintenance and changes; I would be inclined to use a std::unique_ptr and avoid the risk of any future memory leaks.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.