C++ Linked Lists   «Prev  Next»
Lesson 8A singly linked list
ObjectiveThe release() member function

C++ release() function

C++ has a `release()` member function, but it's specifically associated with smart pointers in the standard library. Here's what you need to know:
Smart Pointers and release() Smart pointers are classes that help manage memory dynamically allocated with `new`. They automatically handle deleting the memory they manage when they go out of scope. The `release()` function is part of: * **`std::unique_ptr`: A smart pointer designed to have exclusive ownership of a dynamically allocated object. Purpose of release() The primary purpose of `release()` is to transfer ownership of the managed object from the `std::unique_ptr` to another entity (like a raw pointer) without deleting the object itself. Here's a basic example:
#include <memory>

int main() {
    std::unique_ptr<int> ptr(new int(5)); 
    int* raw_ptr = ptr.release();  // ptr no longer owns the memory  

    // Use raw_ptr here 
    delete raw_ptr;   // You must manually delete the memory now
Key Points:
  • Caution: After calling `release()`, the `unique_ptr` no longer manages the memory. You're responsible for deleting it using `delete` when you're finished with the raw pointer.
  • Use Cases: `release()` can be helpful when you need more control over the object's lifetime or when passing the ownership of the object to a function or library that expects raw pointers.

Examine the release() member function of the singly linked list implementation.

The release function is used to return all list elements to free store. It marches down the list doing so.
//elements returned to free store
void slist::release()
   while (h != 0)
Each element of the list should be returned to free store in sequence. This is done for a single element by slist::del(), which manipulates the hidden pointer h. Since we are destroying the list, it is unnecessary to preserve the original value of pointer h. This function's chief use is as the body of the destructor slist::~slist(). We could not use a destructor written

   delete h;
because it deletes only the first element in the list.
SEMrush Software