C++异常被捕获延迟,可能导致这种情况的原因是什么?

C++ Exception is Caught Late, what may cause this?

本文关键字:情况 是什么 异常 延迟 C++      更新时间:2023-10-16

我在main.cpp中有以下代码:

#include <iostream>
#include "Matrix.h"
int main(){
mtm::Dimensions dim_1(2,3);
try{
const mtm::Matrix<int> mat_1 = mtm::Matrix<int>::Diagonal(2,1);
mtm::Matrix<int> mat_2 = mtm::Matrix<int>::Diagonal(2,-1);
std::cout<<(-mat_2)(1,1)<<(-mat_2)(2,2)<<std::endl;
} catch(mtm::Matrix<int>::AccessIllegalElement& e){
std::cout<<e.what()<<std::endl;
}
}

虽然它应该给我以下输出:

Mtm matrix error: An attempt to access an illegal element

它返回以下内容:(开头的通知 1(

1Mtm matrix error: An attempt to access an illegal element

以下是我在Matrix.h中实现operator<<的方式:

template<typename T>
std::ostream &operator<<(std::ostream &os, const Matrix<T> &matrix) {
typename Matrix<T>::const_iterator it_begin = matrix.begin();
typename Matrix<T>::const_iterator it_end = matrix.end();
return printMatrix(os, it_begin, it_end, matrix.width());
}

而 printMatrix(( 代码是:

template<class ITERATOR_T>
std::ostream& printMatrix(std::ostream& os,ITERATOR_T begin,
ITERATOR_T end, unsigned int width){
unsigned int row_counter=0;
for (ITERATOR_T it= begin; it !=end; ++it) {
if(row_counter==width){
row_counter=0;
os<< std::endl;
}
os <<*it<<" ";
row_counter++;
}
os<< std::endl;
return os;
}

什么可能导致此错误,我该如何修复它?

如果缺少任何内容,请告诉我。

语句std::cout << (-mat_2)(1,1) << (-mat_2)(2,2) << std::endl;只不过是编写函数调用链的速记方法。

在 C++17 之前,未指定语句中各个函数参数的计算顺序。

因此,在某些平台上(-mat_2)(1,1)可能会引发异常,而在另一些平台上(-mat_2)(2,2)可能会引发异常。

C++17 之前的一个解决方案是,如果您想更严格地控制行为,请将std::cout分解为单独的语句。

从 C++17 开始,指定顺序,并且必须从(-mat_2)(1,1)引发异常。