为什么C ++中的参数匹配会忽略数组大小? [英] Why does argument matching in C++ ignore array sizes?

查看:73
本文介绍了为什么C ++中的参数匹配会忽略数组大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此示例中,getSize()返回数组的大小。

In this example, getSize() returns the size of an array.

template <class T, size_t N>
size_t getSize(T(&array)[N])
{
   return N;
}

虽然此代码无法编译:

template <class T, size_t N>
size_t getSize(const T array[N])
{
   return N;
}

经过一些研究,我得出结论,这意味着C ++将允许以下内容:

After some research I concluded that this means that C++ will allow something like this:

void func(char c[10]) {}

int main()
{
   char c[5];
   func(c);
}

该代码即使没有生成警告也可以编译的事实令我感到惊讶。如果实现了数组大小检查,它将使代码更安全,并且第二个模板也可以编译并正常工作。
导致这种编译器行为的原因是什么?

The fact that this code compiles without even generating a warning was a surprise to me. If array size checking was implemented, it would make the code safer, and the second template would also compile and work fine. What are the reasons behind such compiler behavior?

推荐答案

就像C ++中的许多其他事情一样,因为C做到了

(C中的许多事情都是这样,因为B或BCPL就是这样做的。)

Like many other things in C++, "because C does it that way".
(And many things in C are the way they are because B or BCPL did it that way.)

在C ++中,在C

void foo(int p[10]);

等价于

void foo(int p[]);

等效于

void foo(int *p);

即参数看起来像数组,但实际上是一个

此函数的数组参数隐式转换为指向其第一个元素的指针。

That is, the parameter looks like an array, but is actually a pointer.
An array argument to this function is implicitly converted into a pointer to its first element.

C和C ++都允许您传递一个 pointer 指向特定大小的数组,例如

Both C and C++ allow you to pass a pointer to an array of a specific size, like this

void foo(int (*p)[10]);

// ...
int a[10];
int b[20];
int *c;
foo(&a); // OK
foo(&b); // Not OK
foo(c);  // Not OK

,然后是C ++对模板所使用的特定大小的数组的引用从那开始。

and C++'s reference to an array of a specific size, which your template uses, follows from that.

这篇关于为什么C ++中的参数匹配会忽略数组大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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