1. new/delete — raw memory
new Tallocates + constructs →delete t;.new T[n]→delete[] arr;— array form must match, mismatch = UB.newfrom function-local → must eventually delete, else leak.- Prefer containers / smart pointers over raw new/delete.
2. RAII — the cornerstone
Resource Acquisition Is Initialization:
- Acquire resource in constructor, release in destructor (guaranteed at scope end).
- No leak on exceptions — destructors run during stack unwinding.
- Examples:
std::string,std::vector,std::ifstream,std::mutex, smart pointers.
class File {
public:
explicit File(const char* name) : fp_(fopen(name, "r")) {}
~File() { if (fp_) fclose(fp_); }
private:
FILE* fp_;
};
3. Smart pointers
| Type | Meaning |
|---|---|
unique_ptr<T> | sole ownership, move-only |
shared_ptr<T> | shared ownership via refcount |
weak_ptr<T> | non-owning observer of shared_ptr |
shared_ptr— copies increment a refcount; last owner destroyed → deletes.weak_ptr— breaks reference cycles; must.lock()to get a validshared_ptr.unique_ptrhas no reference-counting overhead.
auto p = std::make_shared<int>(42); // single allocation
std::cout << p.use_count(); // 1
std::weak_ptr<int> w = p; // doesn't increase count
auto sp = w.lock(); // returns shared_ptr if alive, else null
make_shared/make_unique— exception-safe single allocation.
4. Move semantics
- Rvalue expressions are about-to-be-destroyed temporaries;
T&&binds to them. - Move constructor “steals” resources; source left in valid-but-unspecified state.
std::move(x)casts to rvalue — doesn’t actually move, enables the move ctor/assignment.
std::vector<int> a(1000000);
std::vector<int> b = std::move(a); // steals a's buffer, a is now empty
- Copy = deep duplicate; move = cheap ownership transfer.
- Hidden copies vs moves: returning by value moves/multiple by NRVO in modern compilers.
5. Value categories — the essential model
- lvalue: has a name / addressable —
x,m.field. - rvalue: temporary —
42,f(),std::move(x). int&& r = 42;extends lifetime of42; rvalue refs mainly enable move and perfect forwarding.
6. Interview checkpoint
- RAII — why destructors clean up automatically.
- unique_ptr vs shared_ptr vs weak_ptr; refcount and cycles.
- make_shared single allocation; weak_ptr.lock().
- Move vs copy; what
std::movedoes (typecast, not steal). - When leaking is impossible in idiomatic code.
Premium Content
Unlock Part 3: Memory, Smart Pointers & Move Semantics and all premium lessons with a subscription.
All premium lessons
Ad-free experience
Priority support
From ₹199.99/year — See plans