cls*_*udt 6 c++ exception vector googletest
我用googletest测试我的C++代码.当vector::_M_range_check
因为std::vector
使用错误索引访问a 而引发异常时,googletest会报告:
C++ exception with description "vector::_M_range_check" thrown in the test body.
Run Code Online (Sandbox Code Playgroud)
太好了,现在我也想知道哪个矢量,哪个指数和哪个范围.如何轻松获取此信息,将测试代码保留在googletest单元测试用例中?
(我几乎从Java开始,其旧的IndexOutOfBoundsException ...)
如果您使用此命令行选项运行,那么您的异常将一直冒出:
--gtest_catch_exceptions=0
Run Code Online (Sandbox Code Playgroud)
在调试器内执行此操作将为您提供异常的堆栈跟踪.
此处不涉及Google Test.您的C++标准库实现引发了异常,并且由C++标准库实现来决定如何使其异常变得冗长.
既然你得到一个例外,我假设你正在使用std::vector::at
的不是std::vector::operator[]
.您可以采取几种方法来获取更多信息.
首先,您可以将调用替换为at
调用operator[]
(个人而言,我发现at
异常抛出范围检查非常有用,并且确实存在性能开销)并使用C++标准库实现的迭代器调试.例如,使用g ++,如果我使用operator[]
并编译-D_GLIBCXX_DEBUG
以打开范围检查operator[]
,我会收到类似于以下内容的错误:
/usr/include/c++/4.3/debug/vector:237:error: attempt to subscript container
with out-of-bounds index 0, but container only holds 0 elements.
Run Code Online (Sandbox Code Playgroud)
其次,您可以将呼叫替换为at
对test_at
类似或类似的呼叫:(未经测试)
template <typename T>
T& test_at(std::vector<T>& v, size_t n) {
// Use Google Test to display details on out of bounds.
// We can stream additional information here if we like.
EXPECT_LT(n, v.size()) << "for vector at address " << &v;
// Fall back to at, and let it throw its exception, so that our
// test will terminate as expected.
return v.at(n);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4403 次 |
最近记录: |