Domanda

I have a question about better programming practice. Say, I have the following class:

class MyClass {
public: 
    vector<double> data() { return data_; }
    void set_data(int index, double value) { data_[index] = value; }
private:
    vector<double> data_;
};

I have the private vector data_ and accessor/mutator functions to that. Using operator= in case of public data_ is very convenient. However, I need to make the data_ private and access/mutate it through member functions. But I am not sure of the best way to construct the mutator function. The best way I have so far is the one in the example. Any suggestions?

È stato utile?

Soluzione

It depends what you want to do with the class but I would suggest:

double getAt(size_t index) const { return data_.at(index); }
void setAt(size_t index, double value) { data_.at(index) = value; }

This has the advantage that you could change the internal implementation of the class, e.g to use a different STL container, and you would not need to change the interface. Note that the getter is const.

If performance is critical and you trust the callers then you can omit the bounds checking:

double getAt(size_t index) const { return data_[index]; }
void setAt(size_t index, double value) { data_[index] = value; }

But it may be useful to be able to set the whole vector and you don't mind exposing the implementation, in which case you might want something like:

void setData(std::vector<double> data) { data_ = std::move(data); }

Note that setData takes the vector by value and moves it into the private member variable this means that if the caller passes an rvalue then no copy is made.

If you need to get the whole vector, you have a choice. If the vector is not too large, performance is not critical or you need to make a copy anyway then return by value is fine and would be my first choice:

std::vector<double> getData() const { return data_; }

Otherwise return by reference:

const std::vector<double>& getData() const { return data_; }
std::vector<double>& getData() { return data_ } 

But be aware that this is completely breaking encapsulation, particularly the non-const version.

Altri suggerimenti

Simplest methods of providing access to the data.

double& at(size_t index) { return data_[index]; }
double const& at(size_t index) const { return data_[index]; }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top