lundi 5 décembre 2016

How to return a reference to an object (from an unordered_map), when the key may not exist?

Say I have an Object:

class Object{
public:
Object(std::vector<int>stuff){

    }
}

Each of these objects is only accessible from a class Foo:

class Foo{
public:
std::unordered_map<int,Object> _objects;

bool getObjectForId(const int& objectId,Object& rep){
     bool found = false;
     std::unordered_map<int, Object>::const_iterator got = _objects.find(objectId);
     if(got != _objects.end()){
        found = true;
        rep = _objects[objectId];
     }
     return found;
}

In some other class I will try to get a reference to an object by doing:

class Other{
private:
   Foo myFoo;
public:

   void changeSomeObjectProperty(const int& objectId){
       Object rep;  
       bool gotIt = myFoo.getObjectForId(objectId,rep);

       //Then I will do some stuff with the rep, if gotIt is true
   }
}

Does this pattern make sense ? I do not want a copy of the object. I want a reference to the object, but I am trying to avoid using pointers...

Aucun commentaire:

Enregistrer un commentaire