为什么我应该在我的捕获块中使用"const"?
Why should I use "const" in my catch block?
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;
}
}
相关文章:
- 我应该使用什么来代替void作为变体中的替代类型之一
- boost::asio::steady_timer()与sleep()我应该使用哪一个
- 违反const正确性:我应该现实地期待什么问题
- C++ 我应该如何解释函数参数long(*pPointer)(OtherClass *const, long)?
- 我应该使用 const shared_ptr<T>&or shared_ptr<T> 作为我的 lambda 函数的参数吗?
- 转发模板参数的const-度,我应该使用转发参考
- 我应该更喜欢在函数中的常数:constexpr const或enum
- 我应该始终使用"T&&"而不是"const T&"或"T&"来绑定到回调函数吗?
- 我应该在简单的访问成员函数中使用 const 返回类型吗?
- 为什么我应该使用 const T& 而不是 const T 或 T&
- 我应该通过const引用传递std::函数吗
- 我应该更喜欢const函数吗
- 为什么我应该在我的捕获块中使用"const"?
- 重新实现std::swap,我应该为tmp变量使用const吗
- 当一个方法只接受 Foo *const 时,我应该const_cast "this"吗?
- 我应该什么时候通过 T const& 返回?
- 我应该使用 const &iterator,还是只使用迭代器?
- 我应该将其声明为类的const int成员变量吗?
- 我应该什么时候传递"T* const&"类型的指针?
- 与const和non-const相同的对象,我应该假设什么行为正确