什么是最好的方法返回只读与可变对象? [英] What is best way to return readonly with changeable objects?

查看:224
本文介绍了什么是最好的方法返回只读与可变对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有容器的对象,我只想返回只读的列表,因为对象是在容器内管理。

I'm having container of objects and i want to return only readonly list of them because objects are managed within container.

class Object;

class Container {
public:
   typedef list<Object*> Objects;

   // first method, probably slow
   Objects getObjects() { return this->objects; }
   // another method, but i don't know if it isn't lacking somewhere else
   Objects::iterator getObjectsIt() { return this->objects.begin(); }
   // OR any better method exists ??

private:
   Objects objects;
};


推荐答案

您可能有一个特殊类型的迭代器不兼容与您的列表的成员函数,它使迭代器改变列表,以便您可以通过迭代器访问对象,但不将它们传递到更改列表的函数属于。

You could have a special type of iterator that was incompatible with the member functions of your list which take iterators to mutate the list, so that you can access the objects through the iterator but not pass them to the functions that change the list they belong to.

假设迭代器不记得它们来自哪个容器。如果他们这样做,那么只是使那个特殊的迭代器类没有可以改变其父容器的函数。

That assumes that iterators don't remember what container they came from. If they do, then just make that special iterator class have no functions that can change its parent container.

这篇关于什么是最好的方法返回只读与可变对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆