std::tr1::array 和 boost::array 之间的区别
我的印象是 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;
}
I was under the impression that std::tr1::array was the same as the boost::array in that it would throw an exception when accessing an index out of bounds. In fact, I took a peek in the header and it appears that way as well. Could someone explain why the following code results in a bus error (gcc version 4.0.1 (Apple Inc. build 5465)) and a segfault on gcc 4.1.2?
Thanks.
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可能是您安装的特定编译器版本中的错误。以下是 GCC 在我的系统 (Linux x86-64) 上对您的代码所做的操作:
因此,这似乎可以全面工作,并且特别说明的是,它似乎在我的 GCC 4.1.2 机器上正常工作,而在您的机器上却失败了。您是否尝试过在崩溃时获取堆栈回溯? Valgrind 也可能有帮助。
It may be a bug in your particular installed version of the compiler. Here's what GCC does for your code on my system (Linux x86-64):
So this seems to work across the board, and it's particularly telling that it seems to work correctly on my machine with GCC 4.1.2 where it fails with yours. Have you tried getting a stack backtrace at the point of the crash? Valgrind also might be helpful.
您正在分配一个包含 3 个元素的数组 (
array
),但您正在尝试访问第 4 个元素 (arr.at(3)
)代码>)。 boost::array 使用断言进行边界检查。我不确定 tr1::array,但是如果您阅读了(草案)C++0x 标准,它不需要array::operator[]()
抛出界限指标。因此,我假设您的 tr1::array 实现的行为与 boost::array 类似(在调试版本中引发断言,在发布版本中不执行任何操作)。这可以解释测试代码中的“总线错误”/“段错误”。You're allocating an array of 3 elements (
array<std::string, 3>
), but you're trying to access the 4th element (arr.at(3)
). boost::array does bounds checking with an assertion. I'm not sure about tr1::array, but if you read the (draft) C++0x Standard, it does not require thearray::operator[]()
to throw on out of bounds indicies. So I assume your implementation of tr1::array is behaving similarily to boost::array (raising an assertion in debug builds, doing nothing in release builds). This would explain the 'bus error'/'segfault' in your test code.