为什么我应该在我的捕获块中使用"const"?

Why should I use "const" in my catch block?

本文关键字:const 我应该 我的 为什么      更新时间:2023-10-16
try
{       
    if (isfull()==1)
        throw "full stack";
    else
        a[top++] = x;
}
catch (const char *s)
{
    cout<<s;
}

为什么我们应该在 catch 块中使用 const?如果我不使用它,我会收到此错误:

terminate called after throwing an instance of 'char const*'  
Aborted (core dumped)

因为您正在抛出字符串文字,而字符串文字与指向常量内存的指针相同,因此需要const

更一般地说,这是因为如果你离开了常量,你的 catch 块没有捕获你抛出的异常。

但是,抛出非异常类型被认为是错误的形式;请考虑抛出从 std::exception 派生的std::runtime_error或其他类型。您可以使用字符串构造其中的大多数,并从 what() 属性获取消息。

您仍然应该通过 const 引用来捕获这些内容,以防止复制和修改捕获的对象(这在任何情况下都不是有用的东西(:

try
{
    throw runtime_error( "full stack" );
}
catch( const runtime_error & x )
{
    cout << x.what();
}
catch( const exception & x )
{
    // catch other exceptions derived from this base class.
}

你的try块抛出一个const类型的字符串:"full stack",这并不意味着在你的catch块中改变。

在任何情况下,常量字符 * 都不能隐式转换为字符 *。

如果 catch 接收 char *s 参数,则 s 指向的内容可能会被 s[...] 赋值更改,这是不可接受的,因为内容("完整堆栈"(是恒定的。

因为您可以将限定符较少的变量隐式分配给限定符较多的变量但是您不能隐式地将 MORE 限定符的变量分配给限定符较少的变量

例如

foo(char * p)
fooc(const char * p)
int main(int argc, char agrv[]) {
  const char* cp = "hello";
  char* p = new char[10];
  foo(cp); // ==> compilation error
  strcpy(p,  cp);
  fooc(p) // No probs assigning to a more qualified var
}

这就是为什么@Joachim皮勒堡是对的:)

没那么简单。问题是在C++中表现出一些东西。我们可以将"const char*"字面分配给"char*">

char* ss = "full stack"; //ok, although "full stack" looks like a const char*
const char* s2 = "full stack";
char* ss = s2 ; //not ok

为了照顾 C 程序,C++允许:char* ss = "全栈";顺便一提。在我的VS2005编译器中,什么也没发生(没有核心转储(。

void main(){
    try
    {       
        throw "full stack";
    }
    catch (char *s)
    {
        std::cout << s <<std::endl;
    }
}