Skip to main content

Lesson 3 of 5

Full String Class - Implementing All Five

Implementing a custom `String` class from scratch - owning `char*` data, null-terminated, with all five special members - is the canonical exercise for mastering the Rule of 5. Every C++ programmer should be able to write this. It tests memory ownership, const-correctness, operator overloading, exception safety, and noexcept move semantics simultaneously.

14 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

MyString - Complete Implementation with All 5 Specials

MyString - Complete Implementation with All 5 Specials
#include <iostream>
#include <cstring>
#include <algorithm>
#include <stdexcept>
#include <cassert>

class MyString {
    char*  data_;   // always null-terminated, never null (empty = "")
    size_t size_;   // length excluding null terminator

    // Helper - allocate and copy
    static char* make_copy(const char* src, size_t len) {
        char* p = new char[len + 1];
        std::memcpy(p, src, len);
        p[len] = '';
        return p;
    }

public:
    // ── 1. Default constructor ────────────────────────────────
    MyString() : data_(new char[1]{''}), size_(0) {}

    // ── Conversion constructor (allows: MyString s = "hello";) ─
    /*implicit*/ MyString(const char* str) {
        if (!str) throw std::invalid_argument("null char*");
        size_ = std::strlen(str);
        data_ = make_copy(str, size_);
    }

    MyString(const char* str, size_t len)
        : data_(make_copy(str, len)), size_(len) {}

    // ── 2. Copy constructor ───────────────────────────────────
    MyString(const MyString& other)
        : data_(make_copy(other.data_, other.size_))
        , size_(other.size_) {}

    // ── 3. Copy assignment - copy-and-swap ────────────────────
    MyString& operator=(MyString other) noexcept {
        std::swap(data_, other.data_);
        std::swap(size_, other.size_);
        return *this;
    }

    // ── 4. Move constructor ───────────────────────────────────
    MyString(MyString&& other) noexcept
        : data_(other.data_), size_(other.size_) {
        other.data_ = new char[1]{''};   // leave in valid empty state
        other.size_ = 0;
    }

    // ── 5. Destructor ─────────────────────────────────────────
    ~MyString() { delete[] data_; }

    // ── Accessors ─────────────────────────────────────────────
    const char* c_str()   const noexcept { return data_; }
    size_t      size()    const noexcept { return size_; }
    bool        empty()   const noexcept { return size_ == 0; }

    char& operator[](size_t i) {
        if (i >= size_) throw std::out_of_range("MyString::operator[]");
        return data_[i];
    }
    const char& operator[](size_t i) const {
        if (i >= size_) throw std::out_of_range("MyString::operator[]");
        return data_[i];
    }

    // ── Concatenation ─────────────────────────────────────────
    MyString& operator+=(const MyString& rhs) {
        char* new_data = new char[size_ + rhs.size_ + 1];
        std::memcpy(new_data, data_, size_);
        std::memcpy(new_data + size_, rhs.data_, rhs.size_ + 1);
        delete[] data_;
        data_  = new_data;
        size_ += rhs.size_;
        return *this;
    }

    // ── Comparison ─────────────────────────────────────────────
    bool operator==(const MyString& o) const noexcept {
        return size_ == o.size_ && std::memcmp(data_, o.data_, size_) == 0;
    }
    bool operator!=(const MyString& o) const noexcept { return !(*this == o); }
    bool operator< (const MyString& o) const noexcept {
        return std::strcmp(data_, o.data_) < 0;
    }

    friend MyString operator+(MyString a, const MyString& b) {
        return a += b;
    }

    friend std::ostream& operator<<(std::ostream& os, const MyString& s) {
        return os.write(s.data_, s.size_);
    }

    // ── find ──────────────────────────────────────────────────
    size_t find(char ch) const noexcept {
        for (size_t i = 0; i < size_; ++i)
            if (data_[i] == ch) return i;
        return npos;
    }
    MyString substr(size_t start, size_t len = npos) const {
        if (start > size_) throw std::out_of_range("substr start");
        len = std::min(len, size_ - start);
        return {data_ + start, len};
    }

    static constexpr size_t npos = static_cast<size_t>(-1);
};

int main() {
    MyString s1 = "Hello";   // conversion ctor
    MyString s2 = " World";
    MyString s3 = s1 + s2;   // copy + +=

    std::cout << s3 << "
";  // Hello World

    MyString s4 = std::move(s3);  // move ctor - s3 becomes empty
    std::cout << s4 << "
";
    std::cout << "s3 empty: " << s3.empty() << "
";  // 1

    s4[0] = 'h';  // subscript
    std::cout << s4 << "
";  // hello World

    std::cout << (s4 < s2) << "
";   // 0 ('h' > ' ')

    auto pos = s4.find('W');
    std::cout << "W at " << pos << "
";                  // 6
    std::cout << s4.substr(pos, 5) << "
";               // World

    // noexcept checks
    static_assert(noexcept(std::declval<MyString>().size()));
    static_assert(noexcept(MyString(std::declval<MyString&&>())));  // move ctor

    return 0;
}

Common Mistakes

  • Not leaving the moved-from object in a valid state - after the move constructor, the source must be destructible. `other.data_ = nullptr` then `delete[] nullptr` in the destructor is technically OK (deleting nullptr is a no-op), but a better practice is to set it to an empty valid state: `other.data_ = new char[1]{}`.
  • Off-by-one in `operator+=` - the `memcpy` for rhs must include the null terminator: `memcpy(new_data + size_, rhs.data_, rhs.size_ + 1)`. The `+1` copies the `null terminator (\x00)`. Forgetting it leaves the string without a null terminator - undefined behaviour on any `c_str()` use.
  • Combined copy/move assignment with single `operator=(MyString other)` - this works but has a subtle inefficiency for self-assignment: `s = s` copies `s` into `other` (the parameter), then swaps. The copy is unnecessary. For `std::string`-like types with frequent self-assignment, separate operators are more efficient.

Tip

Tip

Practice Full String Class Implementing All Five in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Implementing all five special member functions with deep copy and move semantics

Practice Task

Note

Practice Task - (1) Write a working example of Full String Class Implementing All Five from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Full String Class Implementing All Five is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Key Takeaways

  • Implementing a custom `String` class from scratch - owning `char*` data, null-terminated, with all five special members - is the canonical exercise for mastering the Rule of 5.
  • Not leaving the moved-from object in a valid state - after the move constructor, the source must be destructible. `other.data_ = nullptr` then `delete[] nullptr` in the destructor is technically OK (deleting nullptr is a no-op), but a better practice is to set it to an empty valid state: `other.data_ = new char[1]{}`.
  • Off-by-one in `operator+=` - the `memcpy` for rhs must include the null terminator: `memcpy(new_data + size_, rhs.data_, rhs.size_ + 1)`. The `+1` copies the `null terminator (\x00)`. Forgetting it leaves the string without a null terminator - undefined behaviour on any `c_str()` use.
  • Combined copy/move assignment with single `operator=(MyString other)` - this works but has a subtle inefficiency for self-assignment: `s = s` copies `s` into `other` (the parameter), then swaps. The copy is unnecessary. For `std::string`-like types with frequent self-assignment, separate operators are more efficient.

Topics in This Module

0/5 done