在 C++ 中通过指针传递数组的严格规则背后的原因是:标准
在 C++ 中,将数组传递给函数的唯一方法是通过指针,考虑以下因素 函数:
void someFunc(sample input[7]){
//whatever
}
void someFunc(sample input[]){
//whatever
}
void someFunc(sample (& input)[7]){
//whatever
}
当函数未内联时,所有上述函数参数与以下函数参数相同:
void someFunc(sample * input){
//whatever
}
现在要传递带有值的数组,我们必须将其放入如下结构中:
struct SampleArray{
public:
sample sampleArray[7];
};
现在我想知道是否有人知道背后的原因C++ 标准中的这种设计使得任何语法都无法按值传递纯数组,并强制使用结构。
In C++ the only way to pass an array to a function is by pointer, considering following
functions:
void someFunc(sample input[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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
向后兼容的原因。 C++别无选择,只能从C继承这种行为。
Backward compatibility reasons. C++ had no choice but to inherit this behavior from C.
这个答案 之前的类似问题解决了在 C 中引入这种行为的原因(或者更具体地说,为什么该语言以不同的方式处理数组和结构中的数组)。
C++ 采用了 C 的这一部分,但添加了通过引用传递数组的功能(请注意,第三个版本的
someFunc
通过引用传递数组,并不等同于使用指向其第一个元素的指针) 。此外,C++ 包含各种可以按值传递的容器类型(最近包括std::array
)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 includingstd::array
)可能是其 C 血统的函数。数组只是指向内存的指针,在不由编译器生成额外代码的情况下透明地完成这一点有点困难。此外,实现一个在写入时执行延迟复制的容器类也很简单,这会表现得更好。
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.