4

我的印象是 std::tr1::array 与 boost::array 相同,因为它会在访问越界索引时抛出异常。事实上,我看了一眼标题,看起来也是这样。有人可以解释为什么以下代码会导致总线错误(gcc 版本 4.0.1(Apple Inc. build 5465))和 gcc 4.1.2 上的段错误吗?

谢谢。

#include <exception>
#include <iostream>
#include <string>
#include <tr1/array>
#include <boost/array.hpp>

int main()
{
    // boost::array<std::string, 3> arr;
    std::tr1::array<std::string, 3> arr;
    try
    {
        arr.at( 0 ) = "one";
        arr.at( 1 ) = "two";
        arr.at( 2 ) = "three";
        arr.at( 3 ) = "nogood";
    }
    catch ( const std::exception& e )
    {
        std::cout << "exception: " << e.what() << std::endl;
    }
    return 0;
}
4

2 回答 2

4

这可能是您安装的特定编译器版本中的错误。这是 GCC 在我的系统 (Linux x86-64) 上为您的代码所做的:

$ g++-4.1.2 test.cpp -o test
$ ./test
exception: array::_M_at
$ g++-4.3.5 test.cpp -o test
$ ./test
exception: array::at
$ g++-4.4.4 test.cpp -o test
$ ./test
exception: array::at
$ g++-4.5.0 test.cpp -o test
$ ./test
exception: array::at

因此,这似乎可以全面发挥作用,并且特别说明它似乎可以在我的带有 GCC 4.1.2 的机器上正常工作,而在你的机器上却失败了。您是否尝试过在崩溃时获取堆栈回溯?Valgrind 也可能会有所帮助。

于 2010-06-23T13:14:53.163 回答
0

您正在分配一个由 3 个元素 ( ) 组成的数组array<std::string, 3>,但您正在尝试访问第 4 个元素 ( arr.at(3))。boost::array 使用断言进行边界检查。我不确定 tr1::array,但如果您阅读(草案)C++0x 标准,它不需要array::operator[]()抛出越界索引。所以我假设你的 tr1::array 实现的行为类似于 boost::array (在调试版本中提出断言,在发布版本中什么都不做)。这将解释测试代码中的“总线错误”/“段错误”。

于 2010-06-23T13:40:55.400 回答