2
\$\begingroup\$

I have a class Record which keeps entries of strings(implemented using vector of strings). I want to keep the data member private to the class. To get entries, I have defined a member function get_entry which accepts a reference to vector of strings to store results.

Below is the code.

#include <iostream>
#include <vector>
#include <string>

class Record {
public:
        void add_entry(const std::string& entry)
        {
                static int seq = 1;
                entries.push_back(std::to_string(seq++) + " "+ entry);
        }
        void get_entry(std::vector<std::string>& res) const
        {
                for (auto &v: entries)
                        res.push_back(v);
        }

private:
        std::vector<std::string> entries;
};

int main()
{
        Record name;
        name.add_entry("abc");
        name.add_entry("def");
        std::vector<std::string> res;
        name.get_entry(res);
        for (auto &v : res)
                std::cout << v << "\n";
        return 0;
}

Are there other better ways to get entries from such a class? I don't want to make entries data member public and access it directly.

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

The obvious downside of your current approach is that you do a lot potentially unnecessary copying. One common solution is to return (const) iterators to the entries, i.e.,:

class Record
{
    public:
        // ...

       auto cbegin() const { return entries.cbegin(); }
       auto cend() const { return entries.cend(); }

       // Perhaps similar methods for getting non-const iterators ...
};

This solution allows you to use e.g., standard algorithms on the entries, but you can't manipulate the underlying range from the outside (due to const-ness).

To support your earlier use case, you can still do std::vector<std::string> res(r.cbegin(), r.cend()); if you wish, where r is an object of type Record.

\$\endgroup\$
1
\$\begingroup\$

Just return entries by value. It will make a deep copy automatically:

std::vector<std::string> get_entries() const
{
        return entries;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.