1

Given a pointer to an array of N elements of char, I want to create an object which will encapsulate the array (it's address, length and type) giving me a read-only interface to it.

I have been using std::vector but the constructor makes a copy of the original array. I want a solution that avoids the copy.

This is very similar to this existing question: STL non-copying wrapper around an existing array? but I'm trying to avoid maintaining the size and pointer separately and instead have it encapsulated in a single object using a standard library implementation.

Edit: my library processes buffers asynchronously after adding them to a queue. Up until now I have queued the input buffer after copying it into an std::vector. I have just confirmed that the caller will not change the input array till the processing has completed. So, I want to replace the std::vector copy with an object that wraps the original input.

10
  • 7
    std::span Commented Aug 24, 2023 at 12:06
  • 1
    You will need to write a class that implements all requirements of a container, provide its own iterators, etc. How to do this is the same way anything else is done in C++: write the code, test it, see if it works. Your question is unclear. Are you asking if there's a template in the C++ library that will do this for you? There might be something in the ranges library, in the current C++ standard, that will provide a range to play with. Commented Aug 24, 2023 at 12:06
  • 2
    Or boost::span if C++20 is not yet an option Commented Aug 24, 2023 at 12:08
  • 1
    What C++ standard? Is N a compile-time constant, or is it unknown (and read or calculated) at run time? What is the lifetime of the array you're given a pointer to (e.g. can you assume it still exists for as long as the object that provides a read-only interface to it?)? Commented Aug 24, 2023 at 12:15
  • 1
    "Are you asking if there's a template in the C++ library that will do this for you?" That's exactly what I'm asking at the tail end of the post. Commented Aug 24, 2023 at 12:15

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.