首页 > 解决方案 > C++字符串类实现

问题描述

我的项目要求在 C++ 中实现一个字符串类,但是,我对其中一个公共函数感到困惑

class String
{
private:
    char* buffer;
    int size;
    
public:
    // Initializes a string to be empty (i.e., its length will
    // be zero and toChars() will return "").
    String();

    // Initializes a string to contain the characters in the
    // given C-style string, which is assumed to be null-terminated.
    String(const char* chars);

    // Initializes a string to be a copy of an existing string,
    // meaning that it contains the same characters and has the
    // same length.
    String(const String& s);

    // Destroys a string, releasing any memory that is being
    // managed by this object.
    ~String() noexcept;
};

除了String(const char* chars);功能之外,我都正确地实现了它们,但我对如何实现这一点没有任何线索。

编辑:由于不能使用 c++ 标准库,我必须chars通过不使用来计算大小strlen()

String::String(){
    size = 0;
    buffer = nullptr;
}

String::String(const char* chars){
    int i = 0;
    for (char* p = chars;*p != '\0'; p++){
        ++i;
    }
    size = i;

    buffer = new char[size+1];
    i = 0;
    for(;i<size;i++){
        buffer[i] = chars[i];
    }

    buffer[i] = '\0';
}

String::String(const String& s){
    size = s.size;
    buffer = new char[size];
    for int(i=0;i<size;i++){
        buffer[i] = s.buffer[i];
    }
}

String::~String() noexcept{
    delete[] buffer;
}

标签: c++

解决方案


你应该使用std::vector<char>你的缓冲区,这样你就不会显式调用new[]anddelete[]std::vector是 C++ 的一部分(并且已经存在了很长时间),所以这肯定是“在 C++ 中实现 [ing] 一个字符串类 ...”(并且不使用std::string)。

class String final
{
    std::vector<char> buffer;

public:
    String() = default;
    String(const char* chars){
       auto begin = chars;
       auto end = begin + strlen(chars);
       buffer.insert(buffer.begin(), begin, end);
   }
   String(const String& s){
      buffer = s.buffer;
   }
   ~String() = default;
};

注意现在各种构造函数有多简单。这具有避免内存泄漏和异常安全的额外优势;并且您甚至不必(几乎)考虑这些问题。

如果你真的想避免使用std::vector(为什么?它非常适合这种情况),那么至少你应该使用std::unique_ptr<char[]>(或者也许std::shared_ptr<char[]>)添加到 C++11 中。

class String final
{
    std::unique_ptr<char[]> buffer;
public:
    String() = default;
    ~String() = default;
    String(const String&) = delete;
    String& operator=(const String&) = delete;
    String(const char* chars) {
       const auto len = strlen(chars);
       buffer = std::make_unique<char[]>(len + 1);
       strcpy(buffer.get(), chars);
    }
};

您最近的编辑没有多大意义。可以看出,strlen()即使是看似“简单”的功能也很难做好;这就是我们有标准库的原因。如果你不能使用任何标准库,那么甚至没有任何方法可以动态分配内存,就像使用malloc().


推荐阅读