C++: Create a getter using a struct of constant references

Viewed 84

Assuming I have the following class

class Foo {
public:
    // ...
private:
    std::unordered_map<std::string, int> param1;
    std::vector<int> param2;
    // And other complex data types
};    

and want to access the private members of its instance from external function, can I define a structure of constant references to pass them all at once, instead of creating a getter for each one and passing a "zoo" of parameters?

struct params_t {
    const std::unordered_map<std::string, int> &param1;
    const std::vector<int> &param2;
};

params_t Foo::get_params() { return params_t{param1, param2}; }

void bar()
{
    // Initialize an instance of Foo
    params_t params = foo.get_params();
    // Do something with params
}

Is it considered a good practice? Because in my case, my needs are specific: I need all parameters at once and I need them often, so I aim for efficiency and low memory usage rather than code style.

1 Answers

In my opinion it's a code smell, but as long as you can guarantee that the lifetime of the params_t will outlive the Foo that it comes from then it probably isn't a huge issue. The overhead of a couple of getter calls will likely be pretty small though and I would be surprised if the compiler doesn't optimize calls to them out altogether.

Another couple options would be just returning a tuple of references, or maybe something like:

class Foo
{
private:
    struct params_t { ... };
public:
    params_t get_params() const { ... }
};

which would make it harder for consumers to store the params_t (since it's a private member of Foo), or maybe even just making params_t a struct of values (if the params are always used together):

struct params_t {
    std::unordered_map<std::string, int> param1;
    std::vector<int> param2;
};

which Foo could store. get_params() would then return a const& params_t. So many options! Probably up to any code reviewers or personal preference since they'd likely all compile to nearly the same code.

Related