ronag
ronag

Reputation: 51253

RAW pointer container wrapper

I have a raw pointer which points to an array of data. I would like to wrap this pointer into a container with STL container semantics (e.g. std::vector). Does the STL have any feature which allows this?

e.g.

class my_class
{
public:

   std::some_container<char> get_data() { return std::some_container(my_data, my_data_size);}

private:
   char* my_data;
   size_t my_data_size;
};

EDIT:

I cannot use std::vector directly since the memory is allocated by an external api.

Upvotes: 2

Views: 751

Answers (2)

Yakov Galka
Yakov Galka

Reputation: 72489

STL doesn't, boost does:

boost::iterator_range<char*> get_data() { 
    return boost::iterator_range<char*>(my_data, my_data+my_data_size);
}

Upvotes: 5

Jon
Jon

Reputation: 437424

Possibly this is doable if you use std::vector with a custom memory "allocator", but it doesn't sound like a good idea to me.

Since there is no way I know of that would let you get away with this without writing code, I suggest taking the time to write your own STL-like container for this scenario (or better yet, find an open source one!).

Upvotes: 1

Related Questions