Reputation: 103
I am still relatively new to C++, learning as I go, and I'm confused as to what is the 'best' way to expose the vector to its consumers. I'm not worried about performance.
I have a class that contains a vector of raw data
. I have other classes that need to consume and process that vector.
From reading other posts here I'm not sure whether to return a const
reference to the vector or expose const iterators
as none of the consumers will modify the vector.
Is one way better than the other? Are there other options or other things to consider ?
typedef std::vector<int> RawNumberContainer;
typedef std::vector<int>::const_iterator RawNumberIterator;
class RawData
{
public:
RawData();
void addNumber(int number)
{
rawNumbers.push_back(number);
}
// this?
RawNumberContainer getRawNumbers() { return rawNumbers; }
// or this?
const RawNumberContainer& getRawNumbersConstReference() { return rawNumbers; }
// or this?
RawNumberIterator getRawNumbersBeginning() { return rawNumbers.begin(); }
RawNumberIterator getRawNumbersEnd() { return rawNumbers.begin(); }
private:
RawNumberContainer rawNumbers;
};
class Something;
class RawDataConsumer
{
public:
// ??
Something* processRawData(RawNumberContainer&);
// ??
Something* processRawData(const RawNumberContainer&);
// ??
Something* processRawData(RawNumberIterator begin, RawNumberIterator end);
};
Upvotes: 2
Views: 1022
Reputation: 803
It:
const RawNumberContainer& getRawNumbersConstReference() const { return rawNumbers; }
And it:
Something* processRawData(const RawNumberContainer&);
Upvotes: 1
Reputation: 2054
You can use:
RawNumberContainer getRawNumbers() const { return rawNumbers; }
This way you'll make sure you can't edit the vector (only read-only access) and spare you of another variable being manually declared in your code.
Upvotes: 0