I am working on a simple idea and I came across this problem. What happens if after an async call as shown below the program exits without calling shared_future.get()? Will I have a memory leak?
//async function
std::shared_future<double*> sharedFutures = std::async(std::launch::async, myAsyncFunc, argument1, argument2);
if ( realtimeCondition )
{
//what happens to sharedFutures memory allocation after exiting
//memory leak?
return 0;
}
//getting results
for (sharedFuture : sharedFutures )
double* res = sharedFuture.get();
return 0;
shared_future
to some extent mimics std::shared_ptr
. They both manage a shared resource. The resource is released when the last shared_x
is destroyed. This is checked in the destructor (cppreference: https://en.cppreference.com/w/cpp/thread/shared_future/%7Eshared_future):
~shared_future(); (since C++11)
If
*this
is the last object referring to the shared state, destroys the shared state. Otherwise does nothing.
If a class manages a resource it should release it in the destructor. That's true for all classes. The difference here is that the same resource is shared between potentially many objects. So each object has to check if it is the last one to own the resource before it can destroy it.
hence, shared_future destructors are called when exiting and not when having collected the futures via get()?
It would be bad and weird if an object suddenly destroys itself when you call one of its methods. Here specifically, both shared_future
and shared_ptr
would be practically useless if every time you access the object they manage, that object is destroyed. The shared_future
in your example gets destroyed when it goes out of scope.