C++:为什么我对"std :: uninitialized_copy"的调用不起作用?

Kev*_*vin 2 c++ initialization allocator

我构建了一个简单的类,它应该模仿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;
};
Run Code Online (Sandbox Code Playgroud)

为了避免与"new"相关的开销(并增加我对<memory>标题的熟悉程度),我选择使用库的allocator模板类为我的字符串分配内存.以下是我在复制构造函数中使用它的示例:

#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);


}
Run Code Online (Sandbox Code Playgroud)

编译器一直告诉我"uninitialized_copy"行上的两个错误,它们都返回到库中的标题,:

error: invalid conversion from 'char' to 'char*'

error: no match for 'operator!=' in '__first != __last'
Run Code Online (Sandbox Code Playgroud)

问题是我不明白在那一行上从char到char*的转换是什么,以及为什么两个相同类型的指针(str.first,str.onePastLast)不能与"!="进行比较.

我可以使用"新",但如前所述,我想练习<memory>.有人可以告诉我为什么这不起作用?

Unc*_*ens 5

纵观标准raw_storage_iterator不的typedef value_typeT,但它是void不是:

template <class OutputIterator, class T>
class raw_storage_iterator
: public iterator<output_iterator_tag,void,void,void,void>
                                      ^^^^
Run Code Online (Sandbox Code Playgroud)

uninitialized_copy必须使用那个typedef:

template <class InputIterator, class ForwardIterator>
ForwardIterator uninitialized_copy(InputIterator first, InputIterator last,
ForwardIterator result);
Run Code Online (Sandbox Code Playgroud)

功效:

for (; first != last; ++result, ++first)
::new (static_cast<void*>(&*result))
typename iterator_traits<ForwardIterator>::value_type(*first);
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

在您的代码中,在所有替换之后,这会导致:

new (...&*result) void (*first);
                  ^^^^^^^^^^^^^
                 invalid use here
Run Code Online (Sandbox Code Playgroud)

由此可以得出结论,这两者从未打算一起工作.

如果你想使用raw_storage_iterator,那么传递它应该没问题,std::copy因为所有的魔法都发生在operator=(const T&)重载中.

如果你认为任何一个原语是必要的char,你可能只是分配new char[x](NB!终止NUL)并复制strcpy.