Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ designing containers and managing list return

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

like image 878
Andry Avatar asked Nov 25 '10 14:11

Andry


1 Answers

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;
}
like image 177
Armen Tsirunyan Avatar answered Sep 22 '22 07:09

Armen Tsirunyan