C++异常被捕获延迟,可能导致这种情况的原因是什么?
C++ Exception is Caught Late, what may cause this?
我在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)
引发异常。
相关文章:
- 没有可行的过载'='错误,可能导致这种情况的原因是什么?
- 无法访问的代码 在 C++11 中,可能导致这种情况的原因是什么?
- C++异常被捕获延迟,可能导致这种情况的原因是什么?
- 在接口中使用通用指针的原因/正确情况是什么
- 在集合的情况下使用emplace_hint的用例是什么?
- 在这种情况下,int**在C中是什么意思
- 这些情况有什么区别?我怎么知道什么是临时对象?
- 在这种情况下,#define 的作用是什么?
- 在这种情况下,我们可以使用静态而不是朋友吗,还有其他解决方案是什么
- 在不编写显式 setter 的情况下修改私有类数据成员的便捷方法是什么?模板有用吗?
- 在没有额外代码的情况下链接两个独立类的最通用方法是什么?
- 使用c 中的sort()函数对字符串进行排序的最坏情况是什么是什么
- 执行随机开关函数的QT方式是什么连续两次使用相同情况的方法
- 切换情况,用户输入,确定其是什么字符
- 在带有转换运算符的初始值设定项的情况下,复制列表初始化的假定行为是什么
- while(true)可能发生的最坏情况是什么?
- 使用递归进行硬币更改的基本情况是什么
- 这个代码O(R*C)的最坏情况是什么
- 创建临时文件的多种方法:每种方法背后的情况是什么?
- 对于unordered_map,最坏的情况是什么?