我想要一个固定大小的字符串类。理想情况下,该接口(interface)将与 std::string
之一相匹配,唯一的区别是新类从不分配新内存。对于应避免分配新内存的应用程序,它应该是一个方便的类。大小可以是静态的(在编译时已知)。
我认为有两种方式。第一种是围绕 char
数组实现一个类,然后或多或少地实现 std::string
具有的所有功能。我还必须实现一些运算符来创建具有给定固定大小字符串等的 std::string
第二种方法,我什至不确定是否可行,是从 std::string 继承并
覆盖所有可能改变字符串大小的函数。我查看了 Visual Studio 中的 basic_string
header ,它似乎不是虚拟的,所以我想这不是可行的方法。
您认为实现此类的最佳方法是什么?
最佳答案
The first would be to implement a class around a
char
array and then implement more or less all the functions that thestd::string
has.
这绝对是要走的路。它易于编写、易于使用且不易被滥用。
template <size_t N>
class fixed_string {
char array[N+1];
size_t size;
public:
fixed_string() : size(0) { array[0] = '\0'; }
// all the special members can be defaulted
fixed_string(fixed_string const&) = default;
fixed_string(fixed_string&&) = default;
fixed_string& operator=(fixed_string const&) = default;
fixed_string& operator=(fixed_string&&) = default;
~fixed_string() = default;
// ...
};
所有访问器(data
、c_str
、begin
、end
、at
, operator[]
) 是单行代码。所有搜索算法都很简单。
唯一真正的设计问题是您希望突变在失败时做什么。即:
fixed_string<5> foo("abcde");
foo += 'f'; // assert? throw? range-check internally and ignore?
// just not even add this and instead write a
// try_append() that returns optional<fixed_string&>?
设计选择有利也有弊,但无论选择哪一种,每个功能的实现也要非常简洁。
The second method, I'm not even sure is possible, would be to inherit from
std::string
and override all the functions that may change the size of the string. I looked into thebasic_string
header in Visual Studio and it doesn't seem to be virtual, so I guess this is not the way to go.
std::string
中的任何内容是否是virtual
与这是否是一个好主意的问题无关。您肯定希望从以下位置开始:
template <size_t N>
class fixed_string : private std::string { ... }
// ^^^^^^^^^
因为您的类型肯定不符合与 std::string
的 is-a 关系。它不是 std::string
,它只是根据它来实现。私有(private)继承会使这段代码格式错误:
std::string* p = new fixed_string<5>();
因此您不必担心缺少virtual
。
也就是说,从 string
继承将导致比直接路径更复杂、效率更低的实现,并且有更多潜在的陷阱。实现这样的事情可能可能,但我看不出这是个好主意。
关于c++ - 固定大小字符串类的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39171870/