C++设计容器和管理列表返回

发布于 2024-10-04 05:37:32 字数 170 浏览 0 评论 0原文

我正在开发一个类,它充当另一个类的容器。在容器类中,我必须实现一个方法来获取集合中的所有元素。我的容器类使用 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... :) )
Should I return an array?
...
What's the best practice in this context?
Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

护你周全 2024-10-11 05:37:32

恕我直言,最佳实践是使用 迭代器设计模式 并返回迭代器

就您的特定示例而言担心我会做这样的事情:

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;
}

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;
}
滥情空心 2024-10-11 05:37:32

只需包装 begin()end()size()operator[] 即可美好的。

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

栖竹 2024-10-11 05:37:32

迭代器模式很好,但是您正在暴露您的实现细节。它可能会被滥用并破坏你的班级内部结构。这些对于 API 来说都是坏事,您应该设计针对这种情况的保护措施。

这听起来很浪费,但最安全的方法是将集合的副本作为 std::vector 返回。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文