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

标签 c++ return-value compiler-warnings suppress-warnings

我有一个类(此处为MyObject),其中的函数根据对象的内部类型通过引用返回名称。而且,只能对某些内部类型的值调用此函数。

/**
 * \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

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

最佳答案

您可以返回静态变量的引用:

/**
 * \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;
}

关于c++ - 在 Release模式下避免 'control reaches end of non-void function' 警告的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30660773/

相关文章:

c# - 低资源、有针对性和全屏捕获,为什么选择 C#?

python - 带有递归调用的 return 语句如何在 Python 中保存中间值?

delphi - 初始化字符串函数结果?

c++ - 为什么函数在声明为 int 时返回 boolean?

ios - 如何从iOS内部返回方法对象

c# - 为什么警告禁用 429 无法抑制无法访问的代码?

java - 奇怪的 "Resource leak: stream is never closed"如果在循环中抛出异常,则使用 try-with-resources

c++ - 在 Windows 上为 Mac/Linux 编译

c++ - 如何区分两个 std::set<string> 的元素?

c++ - 模板类继承问题