std :: tr1 :: array和boost :: array之间的区别

时间:2010-06-23 12:27:36

标签: c++ boost arrays std tr1

我的印象是std :: tr1 :: array和boost :: array的相同之处在于它在访问超出范围的索引时会抛出异常。事实上,我在标题中看了一眼,看起来也是如此。有人可以解释为什么以下代码导致总线错误(gcc版本4.0.1(Apple Inc.版本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;
}

2 个答案:

答案 0 :(得分:3)

这可能是您特定安装的编译器版本中的错误。以下是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也可能会有所帮助。

答案 1 :(得分:0)

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

相关问题