ProblemsMemory ManagementImplement a String class
IntermediateMemory Management

Implement a String class

Context

The legacy codebase you were moved to 'temporarily, for a quarter' (year three now) bans the STL in its core module — an architect decreed it in 2009 and the decree outlived his tenure. You need a string class: copying, moving, no leaks. Yes, in 2026. No, it's not up for discussion.

Task

Implement a String that owns a heap-allocated character buffer. This is the canonical rule of five interview task: deep copy, safe self-assignment, and move semantics — no algorithms, pure C++ value semantics.

Adapted from exercism/cpp (MIT).

Constraints

  • Own a heap-allocated, null-terminated buffer
  • Deep copy: copies must not share storage
  • Copy assignment must be safe under self-assignment (s = s)
  • Move constructor/assignment transfer the buffer and leave the source empty but valid
  • No leaks: free the buffer in the destructor
  • operator+ returns a new concatenated String

Before you code

  • What goes wrong if the copy constructor does a shallow (pointer) copy?
  • Why must operator= guard against self-assignment?
  • What invariant must a moved-from String satisfy so its destructor is safe?

Tests

  • #1Construct from C-string
  • #2Deep copy is independent
  • #3Self-assignment is safe
  • #4Move leaves source empty
  • #5Concatenation with operator+

Hints

Hint 1

Store an owning char* and the length; always keep a null terminator.

Hint 2

Copy makes a deep copy; move steals the buffer and leaves the source as a valid empty string.

Editorimplement-string.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.

Implement a String class — CppForge