我很想知道将异常对象移动到某个局部变量是否正确。这个 Action 有没有可能导致进入UB?我的担心是因为通过引用捕获假设访问位于其他地方的异常对象(因为它必须一直存在到堆栈展开结束)。请参见下面的示例。
int main()
{
std::pair<int,int> res; //may be heavy object, it's only example
int a[3][5];// assume filled
try
{
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 5; ++j)
{
if(a[i][j] % 2 ==0 )
{
throw std::pair<int,int>(i,j);
}
}
}
}catch(std::pair<int,int>& pair)
{
res = std::move(pair);
}
}
最佳答案
移出的对象仍处于有效状态。
即使您通过 throw;
重新抛出异常,并再次捕获它,它也会起作用。
对于处于有效但未指定状态的对象(假设您使用这样的对象而不是一对整数),结果可能出乎意料,但仍然没有 UB。
关于c++ - 在异常对象上调用 std::move 是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70452948/