Menu

Earn Premium with Referrals

Invite your friends and earn Premium rewards through our referral program.

See how it works and start inviting friends.

Part 3: Memory, Smart Pointers & Move Semantics
C++

Part 3: Memory, Smart Pointers & Move Semantics

Revise new and delete, RAII, unique_ptr, shared_ptr, weak_ptr, move semantics, and copy versus move behavior.

1. new/delete — raw memory

  • new T allocates + constructs → delete t;.
  • new T[n]delete[] arr;array form must match, mismatch = UB.
  • new from 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

TypeMeaning
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 valid shared_ptr.
  • unique_ptr has 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 of 42; 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::move does (typecast, not steal).
  • When leaking is impossible in idiomatic code.

My Private Notes

Notes are auto-saved locally to this device.