I am developing a class which acts as a container for another class. In the container class I must implement a method to get all elements in the collection. My container class uses a std::deque.
Should I return a reference to the deque? Should I return a copy of the deque? (my god tell me this is not the answer... :) ) Should I return an array? ... What's the best practice in this context? Thank you
The best practice IMHO is to use the iterator design pattern and return iterators
As far as your particular example is concerned I would do something like this:
class myContainer
{
public:
typedef std::deque<X> actual_container_type;
typedef actual_container_type::iterator iterator;
typedef actual_container_type::const_iterator const_iterator;
//etc...
iterator begin() {return cont.begin(); }
const_iterator begin() const {return cont.begin(); }
iterator end() {return cont.end(); }
const_iterator end() const {return cont.end(); }
//you may choose to also provide push_front and push_back... or whatever :)
private:
actual_container_type cont;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With