开发者

C++ designing containers and managing list return

开发者 https://www.devze.com 2023-01-26 18:22 出处:网络
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.

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...开发者_JS百科 :) ) 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;
}


Simply wrap begin(), end(), size() and operator[] and you'll be fine.


The iterator pattern is nice but you are exposing your implementation details. It can be abused and break your class internals. These are all bad things for an API and you should design protection against this.

It sounds wasteful but the safest way is to return a copy of your collection as a std::vector.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号