我构建了一个简单的类,它应该模仿 std::string 类的功能(作为练习!):
#ifndef _STR12_1_H
#define _STR12_1_H
#include <string>
#include <iostream>
class Str12_1
{
public:
typedef char* iterator;
typedef const char* const_iterator;
typedef long size_type;
Str12_1();
Str12_1(const Str12_1& str);
Str12_1(const char *p);
Str12_1(const std::string& s);
size_type size() const;
//Other member functions
private:
iterator first;
iterator onePastLast;
iterator onePastAllocated;
};
为了避免与“new”相关的开销(并增加我对<memory>
标题的熟悉度),我选择使用库的分配器模板类来为我的字符串分配内存。这是我在复制构造函数中使用它的示例:
#include <memory>
#include <algorithm>
using std::allocator;
using std::raw_storage_iterator;
using std::uninitialized_copy;
Str12_1::Str12_1(const Str12_1& str)
{
allocator<char> charAlloc;
first = charAlloc.allocate(str.size());
onePastLast = onePastAllocated = first + str.size();
*onePastLast = '\0';
raw_storage_iterator<char*, char> it(first);
uninitialized_copy(str.first, str.onePastLast, it);
}
编译器不断告诉我“uninitialized_copy”行上的两个错误,这两个错误都导致库中的标题,:
error: invalid conversion from 'char' to 'char*'
error: no match for 'operator!=' in '__first != __last'
问题是我不明白从 char 到 char* 的转换在哪一行,以及为什么不能将相同类型的两个指针(str.first、str.onePastLast)与“!=”进行比较。
我可以使用“新”,但如前所述,我想练习<memory>
. 那么有人可以告诉我为什么这不起作用吗?