我有一个类(此处为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/