The reason behind strict rule of passing an array by pointer to a function in C++ standard
In C++ the only way to pass an array to a function is by pointer, considering following functions:
void someFunc(sample inpu开发者_运维百科t[7]){
//whatever
}
void someFunc(sample input[]){
//whatever
}
void someFunc(sample (& input)[7]){
//whatever
}
All above function parameters are identical with following function parameter when the function is not inlined:
void someFunc(sample * input){
//whatever
}
Now to pass the array with value we have to put it in a structure like below:
struct SampleArray{
public:
sample sampleArray[7];
};
Now I'd like to know if anyone knows the reason behind this design in C++ standard that makes passing pure arrays by value impossible by any syntax and forces to use structs.
Backward compatibility reasons. C++ had no choice but to inherit this behavior from C.
This answer to the earlier similar question addresses the reasons why such behavior was introduced in C (or, more specifically, why arrays and arrays within structs are handled differently by the language).
C++ adopted that part of C, but added the ability to pass arrays by reference (note that your third version of someFunc
passes the array by reference, and is not equivalent to using a pointer to its first element). In addition, C++ includes various container types that can be passed by value (recently including std::array
)
Probably as a function of its C ancestry. Arrays being just pointers to memory it'd be kind of hard for that to be done transparently without generating extra code by the compiler. Also it's trivial to implement a container class that does lazy copy on write, which will perform better.
精彩评论