mercredi 6 mai 2015

How to return a const reference which is not available

Say I have the following function:

const std::string& Cat::getKittenName() const
{
  Kitten* kitty = getKitty();
  return kitty->getName();
}

Where Kitten::getName returns a const std::string& how do I best handle the case where kitty is a nullptr? I could return std::string("") but then I am returning a reference to a temporary and practically guaranteeing undefined behaviour. I could change the getKittenName function to return a std::string to get around this but then I am introducing a redundant copy for all the cases where kitty is available. Right now I feel the best option is:

const std::string& Cat::getKittenName() const
{
  Kitten* kitty = getKitty();
  if (kitty)
  {
    return kitty->getName();
  }
  static std::string empty("");
  return empty;
}

The only issue might be if 'magic statics' aren't available. Is there any problem with this solution or is there a better way to do it?

Aucun commentaire:

Enregistrer un commentaire