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 << "Resource acquired." << std::endl; }
~Resource() { std::cout << "Resource released." << std::endl; }
};
int main() {
std::shared_ptr<Resource> res1 = std::make_shared<Resource>();
{
std::shared_ptr<Resource> res2 = res1; // Shared ownership
std::cout << "Inside the block." << std::endl;
} // res2 goes out of scope, but res1 still holds the resource
std::cout << "Exiting main." << std::endl;
return 0;
}
Leave a Reply