将ccyle数组视为std :: array [英] Treat C cstyle array as std::array

查看:140
本文介绍了将ccyle数组视为std :: array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有任何安全和标准的兼容方式来将一个C样式数组作为std ::数组,而不将数据复制到一个新的std ::数组?

Is there any safe and standard compliant way to treat a C style array as an std::array without copying the data into a new std::array?

这显然不编译,但是我想要的效果(我真正的使用是更复杂,但这个简短的示例应该显示我想做的)。我想reinterpret_cast将工作,但可能不安全?

This clearly doesn't compile, but is the effect I would like (my real use is more complicated but this short sample should show what I'd like to do). I guess a reinterpret_cast would "work" but probably isn't safe?

#include <array>

int main()
{
    int data[] = {1, 2, 3, 4, 5};

    // This next line is the important one, treating an existing array as a std::array
    std::array<int, 5>& a = data;
}

感觉应该是可能的,因为数据应该存储相同。

It feels like it ought to be possible as the data should be stored identically.

编辑:要清楚我不想清除一个新的std ::数组,我想引用现有的数据一个。

edit: To be clear I don't want to clear a new std::array, I want to refer to the existing data as one.

推荐答案

你不能这样做。 std :: array 是一个聚合并保存它自己的数据块(相对于一个可以轻松重新分配的数据块的指针)。所以没有办法避免所有元素的副本。在C ++ 11中,这是特别重要的,因为数组的数据不能被移动,所以没有有效的 std :: swap 函数。

You cannot do that. The std::array is an aggregate and holds its own block of data (as opposed to a pointer to a block of data that can be easily reassigned). So there's no way of avoiding a copy of all the elements. In C++11 this is particularly important because the array's data cannot be moved, so there's no efficient std::swap function, for example.

这篇关于将ccyle数组视为std :: array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆