没有访问向量中的任何索引的分割错误
C ++ - Segmentation fault without accessing any index in a vector
我试图重载数组下标操作符,并为[]
操作符提供自定义异常处理机制。使用at()
对向量进行索引,代码捕获异常,但随后崩溃为分段错误。
下面是示例代码
/* MySQLQueryResult.cpp */
class MySQLQueryResult : public mysqlpp::StoreQueryResult {
...
const mysqlpp::Row& MySQLQueryResult::operator[]( int index ) const
{
try {
std::cout << " Called Array Subscript " << this->size( ) << std::endl ;
if ( this->size() > 0 && this->size() > index ) {
return this->at( index ) ;
} else {
throw std::out_of_range("Index out of range");
}
} catch ( std::exception& excpn_ob ) {
std::cout << " Exception caught : " << excpn_ob.what( ) << std::endl ;
}
}
...
}
/* QueryRow.cpp */
class QueryRow : public mysqlpp::Row {
const mysqlpp::String& QueryRow::operator[]( int index ) const
{
try {
std::cout << " Called Array Subscript In Row : " << this->size( ) << " " << std::endl ;
std::cout << index << std::endl;
if ( this->size() > 0 && this->size() > index ) {
return this->at( index ) ;
} else {
throw std::out_of_range("Index out of range");
}
} catch ( std::exception& excpn_ob ) {
std::cout << " Exception caught : " << excpn_ob.what( ) << std::endl ;
}
}
}
/* main.cpp */
int main() {
MySQLQueryResult res = getConfirmationData( ( string ) row.at( 0 ) ) ;
QueryRow qm = res[0];
cout << qm[2] << endl ; // this prints "Bill Watson"
cout << qm[10] << endl; // this prints "Exception caught : Index out of range" and then gives a Seg fault and crashes
mysqlpp::String srt = qm[10]; // this prints "Exception caught : Index out of range" and then gives a Seg fault and crashes
}
所以我得到两个程序消息"调用数组下标"answers"调用数组下标在行",但随后它捕获异常,然后崩溃。我特别使用at()
是为了捕捉这种超出范围的异常,并防止程序崩溃,因为它是一个长时间运行的代码。但是在这里,特别是在QueryRow::operator[]
中,它捕获了异常,然后崩溃。我怎样才能避免这个故障呢?请告诉我如何解决这个问题。
我认为分割错误是因为您正在使用返回值qm[10]
进行计数,但是当捕获异常时,您不返回任何东西。只需调用qm[10]
而不打印它,它应该运行良好。
相关文章:
- 数组索引的值没有增加
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 芬威克树(BIT).找到具有给定累积频率的最小索引,单位为 O(logN)
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 查找最接近的大于当前数字的数字的索引
- 如何在不产生任何垃圾的情况下获得C中的像素
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 在C++中调整向量中的索引
- 重载元组索引运算符-C++
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 为std::string的某个索引赋值
- 并行用于C++17中数组索引范围内的循环
- QTreeView:如果未键入任何内容,则不要更新索引
- 为什么函数的任何索引处的下标运算符在C++中总是返回1
- C++ 复制字符串的指定索引之间的任何子字符串
- CLion 不索引任何外部包含路径
- C++-从单链循环列表中的任何索引中删除一个节点
- g++中用于检查数组索引的任何调试标志
- 没有访问向量中的任何索引的分割错误
- 引用和数组索引之间的任何差异