没有访问向量中的任何索引的分割错误

C ++ - Segmentation fault without accessing any index in a vector

本文关键字:任何 索引 分割 错误 访问 向量      更新时间:2023-10-16

我试图重载数组下标操作符,并为[]操作符提供自定义异常处理机制。使用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]而不打印它,它应该运行良好。