I worked with a class with unique_ptr pointing at object and method set it in runetime asynchroniously to nullptr and then another method might call make_unique and set mentioned pointer to this new object.
void Class0::f0()
{
mPtr = std::make_unique<Class1>();
}
void Class0::f1(SomeType param)
{
mPtr->doWork(param);
mPtr = nullptr;
}
//f1 called after f0 asynchroniously, any number of times
Who and when deletes this previous that was not explicitly deleted? The unique_ptr is still alive since it's a class field so it's destructor is never called, but unique_ptr can be set to nullptr and make_unique can be called many times.
I was almost sure it will cause a memory leak, and mPtr.reset()
must be explicitly called first.
But I've made small test in visual studio c++, that causes no leak.
void f()
{
std::unique_ptr<std::vector<std::vector<int>>> ptr = std::make_unique<std::vector<std::vector<int>>>(100000);
ptr = nullptr;
f();
}
recursion only to check memory usage with and without ptr = nullptr; I've tried WSL g++ with -O0 with the very same result. Can someone explain it please?