ప్రధాన కంటెంట్‌కు వెళ్లండి
eLearner.app
మాడ్యూల్ 7 · 2లో పాఠం 1కోర్సులో 15/18~12 min
మాడ్యూల్ పాఠాలు (1/2)

std::unique_ptr మరియు std::shared_ptr

In classical C++, manual memory management using the new and delete operators is a common source of bugs such as memory leaks (resources never released) or dangling pointers (pointers pointing to deallocated memory).

Modern C++ introduces Smart Pointers, defined in the <memory> header. They automatically manage the lifecycle of heap-allocated memory using RAII (Resource Acquisition Is Initialization), deallocating the resource when the smart pointer goes out of scope.

std::unique_ptr

std::unique_ptr implements the concept of exclusive ownership of a resource. It cannot be copied, only moved (via std::move).

Code
#include <memory>

// Recommended creation using std::make_unique (C++14)
std::unique_ptr<int> p1 = std::make_unique<int>(42);

// Accessing the resource like a normal pointer
std::cout << *p1 << std::endl;

// std::unique_ptr<int> p2 = p1; // COMPILER ERROR: copy not allowed!
std::unique_ptr<int> p2 = std::move(p1); // Allowed: p1 transfers ownership to p2

std::shared_ptr

std::shared_ptr implements the concept of shared ownership. Multiple smart pointers can point to the same resource. The class internally maintains a reference count: the memory is freed only when the last active shared_ptr is destroyed or reset.

Code
#include <memory>

std::shared_ptr<int> s1 = std::make_shared<int>(100);
std::shared_ptr<int> s2 = s1; // Allowed: increments the reference count

std::cout << s1.use_count() << std::endl; // Prints 2 (s1 and s2 share the resource)

Try it yourself

వ్యాయామం#cpp.m7.l1.e1
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

Declare a std::unique_ptr<int> named ptr, initializing it with std::make_unique holding the value 42. Print the dereferenced value of ptr using std::cout.

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

Use `std::unique_ptr<int> ptr = std::make_unique<int>(42);` and then send `*ptr` to the output stream.

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది

వ్యాయామం#cpp.m7.l1.e2
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

Instantiate a std::shared_ptr<int> named ptr1 with the value 100 using std::make_shared. Create a copy named ptr2, and print the value returned by ptr1.use_count() using std::cout.

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

Copying is done via standard assignment: `ptr2 = ptr1;`. Printing `ptr1.use_count()` should display 2.

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది