I building a simple class that is supposed to mimic the functionality of the std::string class (as an exercise!):
#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;
};
In order to avoid the overhead associated with "new" (and to increase my familiarity with the <memory>
header), i've opted to use the library's allocator template class to allocate memory for my string. Here is an example of my use of it in the copy constructor:
#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);
}
The compiler keeps telling me two errors on the "uninitialized_copy" line which both lead back to headers in the library, :
error: invalid conversion from 'char' to 'char*'
error: no match for 'operator!=' in '__first != __last'
The problem is that I don't understand where on that line the conversion from char to char* is, and why two pointers of the same type (str.first, str.onePastLast) cannot be compared with "!=".
I could use "new", but as stated before, I want to get practice with <memory>
. So can someone tell me why this isn't working?
Looking at the standard
raw_storage_iterator
does not typedefvalue_type
to beT
, but it'svoid
instead:whereas
uninitialized_copy
has to use that typedef:Effects:
In your code, after all substitutions, this leads to:
From that you can conclude that those two were never meant to work together.
If you want to use
raw_storage_iterator
, then it should be fine to pass it tostd::copy
since all the magic happens in theoperator=(const T&)
overload.If you think any of this is necessary for a primitive like
char
where you might just allocate withnew char[x]
(NB! terminating NUL) and copy withstrcpy
.