What is the proper modern C++ way to allow access to a member std::vector?

Viewed 178

I have a class which has an array of pointer objects and I'm converting it to a std::vector implementation. I'm new to "modern" c++.

Currently the class exposes the array sort of like this:

class foo
{
private:
    CustomContainer<foo> m_listOfFoos;

public:
    foo  CreateFoo();            // Makes a foo, adds it to the list.
    foo  GetFoo( int i );        // Returns a foo
    int  GetListSize( );         // Returns the number of foos in the list
    void RemoveFoo( int i );     // Removes a foo
    void SortList();             // Sorts the list of foos in a custom way
};

The company uses a custom container written in 2002 and the foo is actually a pointer to a complicated class, but otherwise this is very close to the real situation. I've already started working out the changeover from this container to an std::vector.

What I'm wondering is what is the best modern C++ practice for providing member functions to interact with the container.

Should I update the member functions we already have? Or is there some modern C++ magic that allows me to give access to the container to another class so they can add, remove, and iterate with the vector in a better way?

Is there maybe a way to make the std::vector public but only allow read access? Or a way to return an iterator class that does this?

2 Answers

Unless you have a reason to change the interface (and valid reasons do exist), I wouldn't touch it.

Those valid reasons might include greater familiarity of maintainers, who will have used vectors before but not your custom interface. You could expose your vector by const reference in a const context to prevent modifications.

Mind you, a clear interface like that is not exactly hard to pick up and, this way, you can stick a mutex lock around accesses if you want to. Indeed, the strength of a good interface is that you can swap out its backing data store without exposing that change to any consumers.

In other words, there's really no generic answer to your question, but so far I do not see a reason to change your interface. Certainly, at least in my opinion, the "idiomatic" ways to expose a vector (and/or the reasons not to) haven't changed in recent years.

This looks like a case of misused encapsulation. If outside classes need access directly to your private data member, the member should not be private in the first place. Anyways I would not recommend changing the interface of an existing class, instead the adapter pattern can come in handy if you want to adapt the interface of an existing class to match your new use case.

Related