try和catch中的对象声明未在范围中定义 [英] Object declaration in try and catch not defined in scope

查看:400
本文介绍了try和catch中的对象声明未在范围中定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在try / catch语句中声明一个对象,如下所示:

I would like to declare an object in try / catch statement like this:

try {
  Object object(value);
} catch (exception) {
  return 1;
}
object.usingExemple();

G ++告诉我对象未在范围内定义。

G++ tells me that object is not defined in the scope.

我明白,如果尝试收到一个异常对象没有创建,不能使用。
但是不应该g ++知道我离开函数如果发生了?

I do understand that if try receives an exception object is not created and cannot be used. But shouldn't g++ know that I leave the function if it happens ?

如何声明一个对象在构造函数中抛出异常而不使用new

How could I declare an object that throw an exception in the constructor without using new ?

提前感谢:)

推荐答案

代码使用对象取决于它的创建不会引发异常(它的确如此,因为对象不可用,如果发生异常),那么它覆盖与该对象的相同的条件创建。只需使用 object 将所有代码移动到 try 块:

Simple: if your code using object depends on its creation not raising an exception (it does, since the object is not available if the exception occurs), then it's covered by the same condition as the object's creation. Simply move all code using object into the try block:

try {
  Object object(value);
  object.usingExemple();
} catch (exception) {
  return 1;
}

至于为什么错误本身发生: try 像任何其他大括号一样引入嵌套作用域。该范围中的所有声明都是范围的局部变量,所以 object 不再存在于该范围之外。

As to why the error itself happens: The block statement in try introduces a nested scope just like any other pair of braces. All declarations in that scope are local to the scope - so the identifier object no longer exists outside that scope.

请注意,上面的代码并不完全等同于原始代码,因为 usingExample()引发的异常现在也会被捕获(感谢@immibis指出)。如果这是不可接受的,你必须诉诸动态分配:

Be careful that my code above is not entirely equivalent to your original code, in that exceptions thrown by usingExample() will now also be caught (thanks to @immibis for pointing that out). If that is not acceptable for you, you'll have to resort to dynamic allocation:

std::unique_ptr<Object> objectPtr;
try {
  objectPtr.reset(new Object(value));
} catch (exception)
  return 1;
}
Object &object = *objectPtr;
object.usingExample();

理论上,您也可以使用 new ,但我不建议只是太古怪的解决方案的问题在手:

In theory, you could also use placement new, but I wouldn't recommend that as simply "too weird a solution for the problem at hand:"

alignas(Object) unsigned char objectStorage[sizeof(Object)];
Object *objectPtr;
try {
  objectPtr = new (&objectStorage) Object(value);
} catch (exception) {
  return 1;
}
try {
  Object &object = *objectPtr;
  object.usingExample();
} catch (...) {
  objectPtr->~Object();
  throw;
}

这篇关于try和catch中的对象声明未在范围中定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆