Smart Pointers & Move Semantics
Smart pointers automatically manage dynamically allocated memory using RAII — no manual delete needed. unique_ptr for exclusive ownership, shared_ptr for shared ownership, and move semantics for efficient resource transfer.
45 min•By Priygop Team•Last updated: Feb 2026
Smart Pointer Code
Example
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
class Resource {
string name;
public:
Resource(const string &n) : name(n) { cout << name << " created\n"; }
~Resource() { cout << name << " destroyed\n"; }
void use() const { cout << "Using " << name << endl; }
};
int main() {
// unique_ptr: exclusive ownership (cannot be copied)
auto res1 = make_unique<Resource>("FileHandle");
res1->use();
// auto res2 = res1; // ERROR: cannot copy unique_ptr
// Move ownership
auto res2 = move(res1); // res1 is now nullptr
res2->use();
// res1 is automatically deleted when scope ends
// shared_ptr: shared ownership (reference counted)
auto shared1 = make_shared<Resource>("DBConnection");
{
auto shared2 = shared1; // Copy OK, ref count = 2
cout << "Ref count: " << shared1.use_count() << endl; // 2
shared2->use();
} // shared2 destroyed, ref count = 1
cout << "Ref count: " << shared1.use_count() << endl; // 1
// Resource destroyed when last shared_ptr goes out of scope
// weak_ptr: non-owning reference (breaks cycles)
weak_ptr<Resource> weak = shared1;
if (auto locked = weak.lock()) {
locked->use(); // Safe access
}
// Move semantics (efficient resource transfer)
vector<string> v1 = {"hello", "world"};
vector<string> v2 = move(v1); // v1's data transferred to v2
// v1 is now empty — no copy, just pointer swap!
// Rule of 5: if you define any of: destructor, copy constructor,
// copy assignment, move constructor, move assignment — define all 5
return 0;
}