防止指针作为数组传递

Prevent pointer from being passed as array

所以虽然 common/typical 接受如下 array that has decayed to a pointer

#include <iostream>

void example(int* data)
{
    std::cout << data[0] << ' ' << data[1] << ' ' << data[2] << std::endl;
}

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

我注意到你似乎也可以做相反的事情。也就是说,您可以将一个不会衰减(?)的指针传递回数组

#include <iostream>

void example(int data[3])
{
    std::cout << data[0] << ' ' << data[1] << ' ' << data[2] << std::endl;
}

int main()
{
    int data[3] = {1, 2, 3};
    example(data);
    example(nullptr);  // Is this legal? Can I prevent this?
}

请注意,exampledata 参数已从 int* 更改为 int[3],但我仍然能够通过 nullptr。将参数更改为 std::array<int, 3> 显然可以防止这种情况发生,但我很好奇标准是否描述了这种隐式转换?关于“数组到指针”隐式转换的评论很多,但这似乎是相反的。

事实上,

void example(int data[3])

void example(int data[])

void example(int* data)

你需要

void example(/*const*/ int (&data)[3])

拥有数组引用,(因此拒绝指针或不同大小的数组)。

当你有

void example(int data[3])

该数组本身会衰减为一个指针,因此该函数实际上是

void example(int* data)

这就是为什么您仍然可以将 nullptr 传递给函数的原因。相关段落是 [dcl.fct]/5

The type of a function is determined using the following rules. The type of each parameter (including function parameter packs) is determined from its own parameter-declaration ([dcl.decl]). After determining the type of each parameter, any parameter of type “array of T” or of function type T is adjusted to be “pointer to T”. [...]

强调我的