I’m working on a C++ project where I need to expose some data (specifically a std::vector ) from a class to users of the class. The key requirement is that I want the data to be read-only, and also want to ensure that the elements within the container are read-only aswell. I want to avoid unnecessary copying for performance reasons.
Here are some approaches I’ve considered:
Returning a const std::vector<int>&
— This makes the container read-only, but the elements can still be modified if they’re not const.
Using std::span — Provides a read-only view without copying, but I’m not sure if it’s the best fit for my use case.
I’m curious to hear from others:What are the best practices you’ve found for exposing read-only data in C++?
7
I have an idea that making your read-only data as private fields of your classes, and exposing APIs to provide const random access iterators.
For example:
class Foo
{
public:
std::vector<int>::const_iterator Begin() const
{
return data_.cbegin();
}
std::vector<int>::const_iterator End() const
{
return data_.cend();
}
private:
std::vector<int> data_;
};
1