Return object by reference in c++

43 Views Asked by At

To optimize, I am returning objects by reference since, I do not need to change them, and they can be really large objects. But what if, in case, the underlying object is not present?

Example, consider below code...

map<string,map<string,int> > mMap; 

map<string,int> &  GetReference(string x){
    if(mMap.find(x)==mMap.end()){

    }else{
        return mMap[x];
    }
}

int main()
{
    mMap["abc"].insert(make_pair("cat",1));
    mMap["abc"].insert(make_pair("dog",2));

    map<string,int>& temp = GetReference("abc");
    map<string,int>& temp2 = GetReference("def");

    return 0;
}

Here, temp2 will be an error. So what can be done here?

0

There are 0 best solutions below