I have written below sample code in which objects are created on heap, then wrapped around a unique_ptr, and moved using std::move to another function
void myFunc1( Object<T> &b )
{
for (int i = 0; i < num; i++)
{
std::unique_ptr<T> myt(new T());
b.push(std::move(myt));
}
}
The code does this:
The objects of type T are created using new, and they are managed by a unique_ptr object. That unique_ptr object is passed to one of my class member function b.push(...)
using move semantics:- b.push(std::move(myt));
The function b.push( ) then obtains the managed object pointer of type T from the unique pointer passed to it, and pushes the corresponding object of type T to a queue and returns. EDIT: function b.push -
void Myclass::push(std::unique_ptr<T> uptr)
{
T *tptr = uptr.get();
queue.push(*tptr); // Push the Item object on a std::queue
}
The unique_ptr still holds on to the managed object in this function, until it returns, it does not release, or reset on the unique_ptr.
I am trying to understand if there would be any memory leak in above code.
Would there be any explicit delete needed to de-allocate the objects of type T declared on heap above using new.
Or Is it so that when the unique_pointer passed to member function b.push(...) goes out of scope/it's lifetime ends, the managed object is de-allocated automatically and it's destructor also called and thus no memory leak?
Aucun commentaire:
Enregistrer un commentaire