有人可以解释关于异常的右值引用吗?

发布于 2024-09-26 04:21:43 字数 1288 浏览 6 评论 0原文

可以说我有这个异常类:

struct MyException : public std::exception
{
    MyException(const std::exception &exc) : std::exception(exc)
    {
        cout << "lval\n";
    }
    MyException(std::exception &&exc) : std::exception(std::forward<std::exception>(exc))
    {
        cout << "rval\n";
    }
};

...
...

try
{
    throw std::exception("Oh no!");
    // above is rvalue since it's got no name, what if the throw is made as
    // std::exception lvalExc("Oh wierd!");
    // throw lvalExc;
    // if the throw is made thus, how can it be caught by catch(std::exception &&exc)?
}
catch(std::exception &&rValRef)
{
    cout << "rValRef!\n";
    throw MyException(std::forward<std::exception>(rValRef));
}

当我尝试按值或 (const) 左值引用捕获时。编译器表示这些情况已经由右值引用 catch 子句处理,这是可以理解的,因为例外是 xvalue 也许捕获 xvalue 的最佳方法是右值引用(如果我错了,请纠正我)。但是有人可以解释一下上述异常创建情况下的完美转发吗?正确吗?即使它可以编译,它是否有意义或有用?我使用的 C++ 库是否应该为其 std::exception 实现移动构造函数,以使这种用法真正有意义?我尝试搜索有关异常的右值引用的文章和问题,但找不到任何问题。

Lets say I've this exception class:

struct MyException : public std::exception
{
    MyException(const std::exception &exc) : std::exception(exc)
    {
        cout << "lval\n";
    }
    MyException(std::exception &&exc) : std::exception(std::forward<std::exception>(exc))
    {
        cout << "rval\n";
    }
};

...
...

try
{
    throw std::exception("Oh no!");
    // above is rvalue since it's got no name, what if the throw is made as
    // std::exception lvalExc("Oh wierd!");
    // throw lvalExc;
    // if the throw is made thus, how can it be caught by catch(std::exception &&exc)?
}
catch(std::exception &&rValRef)
{
    cout << "rValRef!\n";
    throw MyException(std::forward<std::exception>(rValRef));
}

When I tried to catch by value or by (const) lvalue ref. the compiler says these cases are already handled by the rvalue ref catch clause, which is understandable, as an exception is an xvalue and perhaps the best way to catch an xvalue is an rvalue ref (correct me if I'm wrong). But can someone explain about the perfect forwarding in the above case of exception creation? Is it correct? Even though it compiles, is it meaningful or useful? Should the C++ library I use have a move constructor implemented for its std::exception for this kind of usage to be truly meaningful? I tried searching for articles and SO questions on rvalue references with respect to exceptions, couldn't find any.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寂寞花火° 2024-10-03 04:21:43

实际上,异常处理对于左值和右值有特殊的规则。临时异常对象是一个左值,参见当前草案的15.1/3:

throw 表达式初始化一个临时对象,称为异常对象,其类型是通过从 throw 操作数的静态类型中删除任何顶级 cv 限定符并调整“T 数组”中的类型来确定的。 ”或“返回 T 的函数”分别为“指向 T 的指针”或“指向返回 T 的函数的指针”。 临时值是一个左值,用于初始化匹配处理程序 (15.3) 中指定的变量。如果异常对象的类型是不完整类型或指向除(可能是 cv 限定的)void 之外的不完整类型的指针,则程序格式错误。除了这些限制和 15.3 中提到的类型匹配限制之外, throw 的操作数完全被视为调用(5.2.2)中的函数参数或 return 语句的操作数。

通过右值引用捕获也是非法的,请参见 15.3/1:

处理程序中的异常声明描述了可能导致进入该处理程序的异常类型。 异常声明不得表示不完整类型或右值引用类型。异常声明不得表示对不完整类型的指针或引用,除了 void*、const void*、volatility void* 或 const volatile void* 之外。

另外,你似乎不太了解完美转发。你的前向调用并不比移动更好。完美转发的思想是将参数的值类别编码为类型的一部分,并让模板参数推导来计算它。但是您的异常处理程序不是也不可能是函数模板。

基本上,完美转发依赖于模板参数推导和右值引用:

void inner(const int&);  // #1 takes only lvalues or const rvalues
void inner(int&&);       // #2 takes non-const rvalues only

template<class T>
void outer(T && x) {
    inner(forward<T>(x));
}

int main() {
   int k = 23;
   outer(k);   // outer<T=int&> --> forward<int&> --> #1
   outer(k+2); // outer<T=int>  --> forward<int>  --> #2
}

根据参数的值类别,模板参数推导将 T 推导为左值引用或普通值类型。由于参考崩溃,T&&在第一种情况下也是左值引用,在第二种情况下也是右值引用。如果您看到 T&& T 是一个可以推导的模板参数,它基本上是“捕获一切”。 std::forward 恢复原始值类别(以 T 编码),因此我们可以完美地将参数转发到重载的内部函数并选择正确的函数。但这仅起作用,因为外部是模板,并且有特殊规则来确定 T 的值类别。如果您使用没有模板/模板参数推导的右值引用(如#2),则该函数将仅接受右值。

Actually, exception handling has special rules with respect to lvalues and rvalues. The temporary exception object is an lvalue, see 15.1/3 of the current draft:

A throw-expression initializes a temporary object, called the exception object, the type of which is determined by removing any top-level cv-qualifiers from the static type of the operand of throw and adjusting the type from “array of T” or “function returning T” to “pointer to T” or “pointer to function returning T”, respectively. The temporary is an lvalue and is used to initialize the variable named in the matching handler (15.3). If the type of the exception object would be an incomplete type or a pointer to an incomplete type other than (possibly cv-qualified) void the program is ill-formed. Except for these restrictions and the restrictions on type matching mentioned in 15.3, the operand of throw is treated exactly as a function argument in a call (5.2.2) or the operand of a return statement.

And catching by rvalue reference is illegal, too, see 15.3/1:

The exception-declaration in a handler describes the type(s) of exceptions that can cause that handler to be entered. The exception-declaration shall not denote an incomplete type or an rvalue reference type. The exception-declaration shall not denote a pointer or reference to an incomplete type, other than void*, const void*, volatile void*, or const volatile void*.

Also, you don't seem to understand perfect forwarding. Your forward invocation is no better than a move. The idea of perfect forwarding is to encode the value category of the argument as part of the type and let template argument deduction figure it out. But your exception handler is not and cannot be a function template.

Basically, perfect forwarding relies on template argument deduction and rvalue references:

void inner(const int&);  // #1 takes only lvalues or const rvalues
void inner(int&&);       // #2 takes non-const rvalues only

template<class T>
void outer(T && x) {
    inner(forward<T>(x));
}

int main() {
   int k = 23;
   outer(k);   // outer<T=int&> --> forward<int&> --> #1
   outer(k+2); // outer<T=int>  --> forward<int>  --> #2
}

Depending on the value category of the argument, template argumend deduction deduces T to be either an lvalue reference or a normal value type. Due to reference collapsing, T&& is also an lvalue reference in the first case, or an rvalue reference in the second case. If you see T&& and T is a template parameter which can be deduced, it's basically a "catch everything". std::forward restores the original value category (encoded in T) so we can perfectly forward the argument to the overloaded inner functions and select the correct one. But this only works because outer is a template and because there are special rules for determining T with respect to its value category. If you use an rvalue references without templates/template argument deduction (like in #2), the function will only accept rvalues.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文