Why does argument matching in C++ ignore array sizes?

╄→гoц情女王★ 提交于 2019-12-08 10:59:57

问题


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

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

While this code does not compile:

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

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?


回答1:


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.)

In C++ as in C

void foo(int p[10]);

is equivalent to

void foo(int p[]);

which is equivalent to

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.

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

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



来源:https://stackoverflow.com/questions/25927772/why-does-argument-matching-in-c-ignore-array-sizes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!