Lightweight container around const char * & length without copying data

I have a basic API that passes const char * and length:

foo(const char* data, const uint32_t len);

I would like to wrap this data / length in a light weight container that can be repeated and has the ability to randomly access but not make a copy (like a vector, for example). What is the best way to achieve this? Const char * data is not necessarily a string; it can contain NULL everywhere.

I use STL and Boost. I saw boost :: as_array <> and as_literal <> - is one of the following here?

+3
source share
3 answers

. - :

template <class T>
class array_ref {
public:
    // makes it work with iterator traits..
    typedef T         value_type;
    typedef size_t    size_type;
    typedef ptrdiff_t difference_type;

    typedef T*        pointer;
    typedef T*        iterator;
    typedef T&        reference;

    typedef const T*  const_pointer;
    typedef const T*  const_iterator;
    typedef const T&  const_reference;

public:
    array_ref(T *p, size_t n) : data_(p), len_(n) {}

    // iteration
    iterator begin()             { return data_; }
    iterator end()               { return data_ + len_; }
    const_iterator begin() const { return data_; }
    const_iterator end() const   { return data_ + len_; }

    // access
    reference operator[](size_t n)             { return data_[n]; }
    reference at(size_t n)                     { return data_[n]; }
    const_reference operator[](size_t n) const { return data_[n]; }
    const_reference at(size_t n) const         { return data_[n]; }

    // capacity
    size_t size() const { return len_; }
    bool empty() const  { return size() == 0; }

    // raw access
    T* data() const { return data_; }

    // etc...
private:
    T* data_;
    size_t len_;
};

, . , , . .

, . , , , .

+4

iterator_facade http://www.boost.org/doc/libs/1_43_0/libs/iterator/doc/iterator_facade.html iterator_range

iterator_range , http://www.boost.org/doc/libs/1_42_0/libs/range/doc/utility_class.html#iter_range

boost::iterator_range<char*> range(begin, begin + N);

iterator_facade

+2

, as_array / as_literal , . , , , , (, , , , , ).

: , , , - , , . comp.lang.++ / comp.lang.++. , , 12 15 , , , ( , , Google ). , - ( ). , , , , (?) as-is - ++ .

0

Source: https://habr.com/ru/post/1754733/


All Articles