kravemir
kravemir

Reputation: 11026

What is best way to return readonly with changeable objects?

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

Upvotes: 0

Views: 178

Answers (2)

Seth Carnegie
Seth Carnegie

Reputation: 75130

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.

Upvotes: 1

cli_hlt
cli_hlt

Reputation: 7164

Return a const_iterator and declare the method const.

Upvotes: 1

Related Questions