C++ primer 丐版String

发布时间 2023-03-22 21:13:41作者: xiazichengxi
class String
{public:
    String() :first_c(nullptr), last_c(nullptr) {};
    String(const char* chr);
    String(const String& s);
    String& operator=(const String& s);
    char* begin() const { return first_c; }
    char* end() const { return last_c; }
    ~String();
private:
    std::allocator<char> alloc;
    std::pair<char*, char*>alloc_n_copy(const String& s);
    void free();
    char* first_c;
    char* last_c;
};

String::String(const char* chr)
{
    auto len = strlen(chr);
    auto beg = alloc.allocate(len);
    first_c = beg;
    last_c = beg + len;
}

String::String(const String& s)
{
    auto p = alloc_n_copy(s);
    first_c = p.first;
    last_c = p.second;
}

String::~String()
{
    free();
}

std::pair<char*, char*> String::alloc_n_copy(const String& s)
{
    auto data = alloc.allocate(s.last_c - s.first_c);
    return { data, std::uninitialized_copy(s.first_c, s.last_c, data) };
}

String& String::operator=(const String& s)
{
    auto tmp = alloc_n_copy(s);
    free();
    first_c = tmp.first;
    last_c = tmp.second;
}


void String::free()
{
    if (first_c)
    {
        std::for_each(first_c, last_c, [this](char &cp) { alloc.destroy(&cp); });
        alloc.deallocate(first_c, last_c - first_c);
    }
}