在 C++ 中通过指针传递数组的严格规则背后的原因是:标准

发布于 2024-10-03 14:06:50 字数 502 浏览 4 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

陌路终见情 2024-10-10 14:06:50

向后兼容的原因。 C++别无选择,只能从C继承这种行为。

Backward compatibility reasons. C++ had no choice but to inherit this behavior from C.

与酒说心事 2024-10-10 14:06:50

这个答案 之前的类似问题解决了在 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 including std::array)

累赘 2024-10-10 14:06:50

可能是其 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文