在发布模式下避免 'control reaches end of non-void function' 警告的最佳方法

Best way to avoid 'control reaches end of non-void function' warning in release mode

我有一个 class(这里是 MyObject),它有一个函数 return 根据对象的内部类型通过引用命名一个名字。而且这个函数只能针对内部类型的某些值调用。

/**
 * \brief Return the name depending of the internal type
 * \pre   The internal type must be 1 or 2
 */
inline
const std::string& MyObject::getName() const
{
  switch(this->type)
  {
    case 1:
      return this->type1->getName();
      break;
    case 2:
      return this->type2->getName();
      break;
    default:
      assert(false && "PRE: Invalid type for this operation");
  }
}

然后,当我在 Release 模式下编译时,我收到这个警告:

warning: control reaches end of non-void function

在这种情况下避免此警告的最佳方法是什么?我不能 return 一个空字符串,因为它会导致引用一个临时对象,然后是另一个警告。我宁愿在这种情况下不抛出异常,因为它只是为了解决警告。如果执行调用默认部分,这是一个编程错误,它将在带有断言的预生产中的调试模式下检测到。通常,执行不会在 Release 模式下调用它,在这种情况下有未定义的行为是可以接受的。

"...it's acceptable to have a random behaviour in this case."

这可能是可以接受的,但你为什么要这样做?只需在 assert 之后添加一个 exit(1);,您就不会花时间在这里,或者编写一个宏来添加 assertexit

另外,您不需要 break 来自 casereturn

您可以return引用静态变量:

/**
 * \brief Return the name depending of the internal type
 * \pre   The internal type must be 1 or 2
 */
inline
const std::string& MyObject::getName() const
{
  switch(this->type)
  {
    case 1:
      return this->type1->getName();
      break;
    case 2:
      return this->type2->getName();
      break;
    default:
      assert(false && "PRE: Invalid type for this operation");
  }

  static std::string hack("");
  return hack;
}