Smart Pointers with std::shared_ptr

This example shows how to use std::shared_ptr for shared ownership of dynamically allocated objects.

cppCopy code#include <iostream>
#include <memory>

class Resource {
public:
Resource() { std::cout &lt;&lt; "Resource acquired." &lt;&lt; std::endl; }
~Resource() { std::cout &lt;&lt; "Resource released." &lt;&lt; std::endl; }
}; int main() {
std::shared_ptr&lt;Resource&gt; res1 = std::make_shared&lt;Resource&gt;();
{
    std::shared_ptr&lt;Resource&gt; res2 = res1; // Shared ownership
    std::cout &lt;&lt; "Inside the block." &lt;&lt; std::endl;
} // res2 goes out of scope, but res1 still holds the resource
std::cout &lt;&lt; "Exiting main." &lt;&lt; std::endl;
return 0;
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *