Como ya se ha dicho, proporcionar acceso const al recipiente.
Pero aún no es "perfecto" porque necesita exponer el contenedor al mundo, por lo que si lo cambia, también obliga al código de usuario a cambiar si la interfaz ya no es la misma.
Pero hay una última esperanza:
Si puede utilizar lambdas (C++ 0x), entonces es mejor que proporcionan un algoritmo for_each:
class MyThingManager
{
public:
template< typename FunctorType > // note : could be non-template, in wich case use std::function<>
void modify_each_thing(FunctorType f) // if you use std::function, you can put the implementation in the cpp file instead of the header/inline
{
// do some checks, or maybe generate a list of Things that you allow to modify
// then apply the function (here we assume we don't have a separate list - implementation defined for the win!)
std::for_each(m_things.begin(), m_things.end(), f); // oh yeah
// then we can apply anything more we want
check_everything_is_still_valid();
notify_the_world();
}
// here is a simpler read-only version
template< typename FunctorType >
void for_each_thing(FunctorType f) const { std::for_each(m_things.begin(), m_things.end(), f); }
// in case you want the user to know how many things to manipulate
size_t things_count() const { return m_things;}
private:
std::vector<Thing> m_things; // could be any container, that's isolated from the algorithm!
};
Uso:
MyThingManager manager;
manager.for_each_thing([](const Thing& thing){ std::cout << "\nA thing : " << thing; });
Puede devolver la referencia const al vector. De esa manera, la persona que llama no puede modificarlo. – Juho
Parece claro de la discusión y responde que estaba implícito que getVectorOfFoo() es una función miembro de una clase y que el vector es una variable miembro de la clase, pero esto no se indicó en ninguna parte de la pregunta, y hace la diferencia . –
Buena discusión, aprendí algo de todos. Gracias chicos. – Mark