const int N = 100;
void function1(int array[]){
// ...
}
void function2(int array[N]){
// ...
}
int main(int argc, char *argv[]){
int a[N] = {1, 2, 3, ... , 100};
function1(a);
function2(a);
return 0;
}
我想知道 function2
是否有可能比 function1
由于某种类型的 C++ 编译器优化(例如,编译器计算出 sizeof(array )
在编译时)。
对于 C,同样的话题之前在这里争论过:Should I declare the expected size of an array passed as function argument? .
谢谢!
最佳答案
两个版本的函数之间应该没有任何性能差异;如果有的话,它可以忽略不计。但是在您的 function2()
中,N 没有任何意义,因为您可以传递任何大小的数组。函数签名不会对数组大小施加任何限制,这意味着您不知道传递给函数的数组的实际 大小。尝试传递一个大小为 50
的数组,编译器不会产生任何错误!
要解决该问题,您可以将函数编写为(它接受类型为 int
且大小为 exactly 100 的数组!):
const int N = 100;
void function2(int (&array)[N])
{
}
//usage
int a[100];
function2(a); //correct - size of the array is exactly 100
int b[50];
function2(b); //error - size of the array is not 100
您可以通过编写接受对类型 T
和大小 N
的数组的引用的函数模板来概括这一点:
template<typename T, size_t N>
void fun(T (&array)[N])
{
//here you know the actual size of the array passed to this function!
//size of array is : N
//you can also calculate the size as
size_t size_array = sizeof(array)/sizeof(T); //size_array turns out to be N
}
//usage
int a[100];
fun(a); //T = int, N = 100
std::string s[25];
fun(s); //T = std::string, N = 25
int *b = new [100];
fun(b); //error - b is not an array!
关于c++ - 是否值得声明作为参数传递的数组的(常数)大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5925537/