谁管理副本构造函数在参数中引发的异常? [英] Who manages the exception thrown by a copy constructor in parameters?

查看:74
本文介绍了谁管理副本构造函数在参数中引发的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有此功能

void foo() noexcept
{
   // Safely noexcept code.
}

然后是此类:

class Bar
{
   Bar(const Bar&) { ... } // Is not noexcept, so might throw
   // Non movable:
   Bar(Bar&&) = delete;
};

现在,我需要修改foo()才能按值接收Bar:

Now, I need to modify foo() to receive a Bar by value:

void foo(Bar bar) // noexcept?
{
   // Safely noexcept code
}

我假设Bar的复制是在调用foo之前完成的,因此从理论上讲foo的代码仍然可以是noexcept,但是我不确定在C ++级别上是如何定义的.foo是否需要删除noexcept或在应对Bar时可能抛出的调用方?它取决于调用模式(stdcall,farcall等)还是编译器?更新:在其他问题中,我没有找到任何有关调用约定的引用.那应该在行为上有所不同.我吃了.

I assume the copy of Bar is done before the call to foo, so the code of foo could theoretically still be noexcept, but I am not sure how is that at C++ level defined. Does foo need to get the noexcept deleted or is the caller who might throw when coping Bar? Does it depend on the call mode(stdcall, farcall, etc..) or compiler? Update: In other questions I did not found any reference to the call convention. That should make a difference on the behavior. I supose.

推荐答案

请参阅[expr.call]/4:

See [expr.call]/4:

每个参数的初始化和销毁​​发生在调用函数.[示例:在调用函数中的调用点检查构造函数,转换函数或析构函数的访问.如果函数参数的构造函数或析构函数引发异常,则在调用函数的范围内开始搜索处理程序;否则,将在调用函数的范围内进行查找.特别是,如果被调用的函数具有 function-try-block (第18条),并且带有可以处理异常的处理程序,则不考虑该处理程序.-最终示例]

The initialization and destruction of each parameter occurs within the context of the calling function. [ Example: The access of the constructor, conversion functions or destructor is checked at the point of call in the calling function. If a constructor or destructor for a function parameter throws an exception, the search for a handler starts in the scope of the calling function; in particular, if the function called has a function-try-block (Clause 18) with a handler that could handle the exception, this handler is not considered. —end example ]

因此,即使可能会初始化 bar ,您仍然可以标记 foo noexcept .调用函数不应为 noexcept .(也就是说,除非您确定程序可以在发生异常情况时终止).

Therefore you can still mark foo noexcept, even though the initialization of bar might throw. The calling function should not be noexcept. (That is, unless you're ok with the program being terminated in case of an exception.)

这篇关于谁管理副本构造函数在参数中引发的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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