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;
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否function2有可能比function1某些类型的C++编译器优化更快(例如,编译器sizeof(array)在编译时计算出来).
对于C,之前已经讨论过相同的主题:我应该声明作为函数参数传递的数组的预期大小吗?.
谢谢!
两个版本的函数之间不应该有任何性能差异; 如果有的话,它可以忽略不计.但是在你的function2()N中并没有任何意义,因为你可以传递任何大小的数组.函数签名不对数组大小施加任何约束,这意味着您不知道传递给函数的数组的实际大小.尝试传递一个大小的数组50,编译器不会生成任何错误!
要解决这个问题,你可以编写函数as(它接受一个类型int和大小恰好为 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
Run Code Online (Sandbox Code Playgroud)
您可以通过编写一个接受对类型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!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
310 次 |
| 最近记录: |