vendredi 23 novembre 2018

const access and non-const access

I have a class which internally owns a vector of foo

class bar {
  private:
    vector<Foo> foos_;
}

Now I want to design public access to this vector. I am thinking of two versions of the function:

Foo& getFoo(int index) {
  // first do size checking, return ref
  return foos[index];
}

and

const Foo& getFoo(int index) {
  // first do size checking, return const reference
  return foos[index];
}

Any downside of this approach? One obvious downside is I copy the almost identical code simply twice. Is there a better way to do this?

Aucun commentaire:

Enregistrer un commentaire