Hazel icon indicating copy to clipboard operation
Hazel copied to clipboard

Memory leak in CreateRef

Open medbensalah opened this issue 2 years ago • 2 comments

Memory leak

In Base.h the CreateRef<> function, make_shared actually creates a new copy to be held by the pointer. This creates a leak whenever used as this way opening a new scene (either empty or from a save file) does not free the previously loaded scene.

image

This can be noticed by following the memory usage.

medbensalah avatar Dec 02 '22 19:12 medbensalah

Hello, I don't think smart pointers can leak memory, because they are designed to solve problems with memory leaks. Although, constexpr is clearly superfluous here. Perhaps you should read about smart pointers to understand me. In any case, you can check if there really is a memory leak (another reason) or if these pointers are being held somewhere, just prolog the calls to the scene's destructors.

NIKEA-SOFT avatar Dec 12 '22 00:12 NIKEA-SOFT

As @NIKEA-SOFT said, there is no memory leaking

  • Compiler inlines this function (constexpr)
  • std::shared_ptr uses reference counting -> previous scene gets deleted
  • example shows:
#include <iostream>
#include <memory>

struct Test {
   Test(int i) {
      std::cout << "Test Constructor! " << i << '\n';
   }
   ~Test() {
      std::cout << "Test Destructor!\n";
      std::cin.get();
   }
};

template<typename T>
using Ref = std::shared_ptr<T>;

template<typename T, typename... Args>
constexpr Ref<T> CreateRef(Args&&... args) {
   return std::make_shared<T>(std::forward<Args>(args)...);
}

int main()
{
   Ref<Test> test = CreateRef<Test>(5);
   // Equivalent of:
   // std::shared_ptr<Test> test = std::make_shared<Test>(5);
}

Peanutt42 avatar Jan 05 '23 23:01 Peanutt42