【问题标题】:Difference between std::tr1::array and boost::arraystd::tr1::array 和 boost::array 之间的区别
【发布时间】:2010-06-23 12:27:36
【问题描述】:

我的印象是 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;
}

【问题讨论】:

  • 我刚刚用 gcc 4.1.2 试了一下,得到了预期的异常。您确定这是您尝试过的确切代码吗?

标签: c++ boost arrays std tr1


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • at 需要检查索引并在必要时为所有实现它的标准序列容器抛出out_of_rangeboost::array&lt;&gt;::at 也一样。
    • 好的,我的立场是正确的。我以某种方式将 operator[] 与 at() 混淆了。
    猜你喜欢
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 2012-05-21
    • 2019-01-28
    • 2016-05-03
    相关资源
    最近更新 更多