假设我有这个异常类:
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) lvalue ref 捕获时。编译器说这些情况已经由 rvalue refcatch
子句处理,这是可以理解的,因为异常是xvalue,也许捕获 xvalue 的最佳方法是 rvalue ref(如果我错了,请纠正我)。但是有人可以解释一下上述异常创建情况下的完美转发吗?这是对的吗?即使它编译,它是否有意义或有用?我使用的 C++ 库是否应该为其实现移动构造函数以std::exception
使这种用法真正有意义?我尝试搜索有关异常的右值引用的文章和 SO 问题,但找不到任何问题。