是否可以将动态分配的数组传递给需要数组引用的函数? [英] Is it possible to pass a dynamically allocated array to a function that requires an array reference?

查看:82
本文介绍了是否可以将动态分配的数组传递给需要数组引用的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

预告:我知道在这里做我想要的事情不是一个好主意.这只是病态语言的好奇心引起的问题,而不是实际使用引起的.我在这里应用的规则完全是任意的.

A note upfront: I know that it's not a good idea to do what I ask for here. This is just a question arising from morbid language curiosity, not from practical use. The rules that I apply here are completely arbitrary.

比方说,我们有一个完全定义如下的函数.只能将其更改为任何其他内容,不允许模板或函数重载.此功能的实现也不得更改(并且可以视为未知).但是我们知道该参数用作out参数.

Let's say we have a function that is exactly defined as the following. It must not be changed to anything but this, no template or function overloading allowed. The implementation of this function must also not change (and can be treated as unknown). We know however that the parameter is used as an out parameter.

void my_func(int (&arr)[10]);

在另一个函数中,我们动态分配一个数组.此分配也必须保持不变,不允许我们在堆栈上进行分配.另外,不允许进一步分配.

In a different function we allocate an array dynamically. This allocation must also not change, we are not allowed to allocate on the stack. Also no further allocations are allowed.

int* my_arr = new int[10];

是否可以通过某种方式调用 my_func 并将其传递给 my_arr ?换句话说,是否有可能欺骗类型系统将 my_arr 视为数组而不是指针?

Is it possible to somehow call my_func and pass it my_arr? In other words, is it somehow possible to trick the type system into treating my_arr as an array rather than a pointer?

单纯的转换并不能解决问题,所有这些都会导致编译错误:

Naïve castings don't do the trick, all of them lead to compile errors:

my_func((int[10])my_arr);
my_func(static_cast<int[10]>(my_arr));
my_func(reinterpret_cast<int[10]>(my_arr));

另一个注意事项:我想欺骗类型系统.我不想从堆栈数组等中复制数据.为什么?再说一次:病态的好奇心.

Another note: I want to trick the type system. I don't want to copy the data from a stack array etc. Why? Again: Morbid curiosity.

推荐答案

您可以为此使用 reinterpret_cast .使用数组类型的别名使代码更易于阅读,您将遇到类似这样的情况:

You can use reinterpret_cast for this. Using an alias for the array type to make the code easier to read, you would have something like:

void my_func(int (&arr)[10])
{
    for (auto e : arr)
        std::cout << e << " ";
}

int main()
{
    using array_t = int[10];
    int* my_arr = new int[10]{1,2,3,4,5,6,7,8,9,10};
    my_func(reinterpret_cast<array_t&>(*my_arr));
}

您会看到在此实时示例中正常工作.

这篇关于是否可以将动态分配的数组传递给需要数组引用的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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