【发布时间】:2018-08-16 20:37:29
【问题描述】:
在 C++ 中是否未定义的行为 像下面的代码那样访问相邻数组中的元素?
#include <type_traits>
#include <algorithm>
#include <iterator>
int main()
{
int a[10][10];
static_assert(std::is_standard_layout< decltype(a) >::value, "!");
std::fill(std::begin(*std::begin(a)), std::end(*std::prev(std::end(a))), 0);
struct B { int b[10]; };
B b[10];
static_assert(std::is_standard_layout< decltype(b) >::value, "!");
std::fill(std::begin(std::begin(b)->b), std::end(std::prev(std::end(b))->b), 0);
}
从技术上讲,我认为对于 POD 类型,以任何方式访问底层内存都是合法的,但是 std::* 的东西呢?
如果我将所有begin/end 更改为rbegin/rend 会怎样?
【问题讨论】:
-
第二种情况,我认为不安全(ideone.com/DyHhgA)第一种,我不知道。
-
将 c 样式的数组
int a[10][10];与 c++ 混合使用永远不会很好。
标签: c++ arrays stl language-lawyer