是否可以将动态分配的数组传递给需要数组引用的函数?
预先说明:我知道在这里做我所要求的不是一个好主意。这只是来自病态语言好奇心的问题,而不是实际使用中的问题。我在这里应用的规则完全是任意的。
假设我们有一个完全定义如下的函数。它不得更改为除此之外的任何内容,不允许模板或函数重载。这个函数的实现也不能改变(并且可以被视为未知)。然而,我们知道该参数用作输出参数。
void my_func(int (&arr)[10]);
在另一个函数中,我们动态分配一个数组。这个分配也不能改变,我们不允许在栈上分配。也不允许进一步分配。
int* my_arr = new int[10];
是否有可能以某种方式调用my_func并传递它my_arr?换句话说,是否有可能以某种方式欺骗类型系统将其my_arr视为数组而不是指针?
朴素的铸造不能解决问题,所有这些都会导致编译错误:
my_func((int[10])my_arr);
my_func(static_cast<int[10]>(my_arr));
my_func(reinterpret_cast<int[10]>(my_arr));
另一个注意事项:我想欺骗类型系统。我不想从堆栈数组等复制数据。为什么?再次:病态的好奇心。
回答
您可以reinterpret_cast为此使用。使用数组类型的别名使代码更易于阅读,您将获得如下内容:
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));
}
你可以在这个活生生的例子中看到这一点。
- @Brotcrunsher It's not required, but it makes life easier. The grammar for arrays is a little complex so to get a reference to an array, you need `int(&)[10]` and the `(&)` in the type tell the compiler that the `&`, or the reference, applies to `int[10]`. Using `int&[10]` wont work as that would be an array of references and that is not allowed. `(int[10])&` also doesn't work as it's jut plain wrong as far as the C++ grammar is concerned.