在 C++ 中传递指针参数,按值传递吗?

Is passing pointer argument, pass by value in C++?(在 C++ 中传递指针参数,按值传递吗?)
本文介绍了在 C++ 中传递指针参数,按值传递吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在 C++ 中传递指针参数,按值传递吗?因为我看到对指针的任何更改都不会反映在方法之外.我通过取消引用指针所做的更改会得到反映.

Is passing pointer argument, pass by value in C++? Since i see that any change to the pointer as such is not reflected outside the method. The changes i do by dereferencing the pointer is reflected though.

在这种情况下,使用指向指针的指针作为函数的参数来修改函数内的指针值是否可以接受/标准程序?

In that case, is it acceptable/standard procedure to use pointer to pointer as argument to a function to modify the pointer value as such within a function?

推荐答案

是的.

指针与其他任何东西一样按值传递.这意味着指针变量的内容(指向的对象的地址)被复制.这意味着如果您更改函数体中指针的值,该更改将不会反映在仍指向旧对象的外部指针中.但是你可以改变指向的对象的值.

Pointers are passed by value as anything else. That means the contents of the pointer variable (the address of the object pointed to) is copied. That means that if you change the value of the pointer in the function body, that change will not be reflected in the external pointer that will still point to the old object. But you can change the value of the object pointed to.

如果要将指针所做的更改反映到外部指针(使其指向其他内容),则需要两个间接级别(指向指针的指针).当调用函数时,它是通过在指针名称之前放置一个 & 来完成的.这是标准的 C 语言做事方式.

If you want to reflect changes made to the pointer to the external pointer (make it point to something else), you need two levels of indirection (pointer to pointer). When calling functions it's done by putting a & before the name of the pointer. It is the standard C way of doing things.

在使用 C++ 时,使用引用优于指针(此后也使用指向指针的指针).

When using C++, using references is preferred to pointer (henceforth also to pointer to pointer).

对于为什么引用应该优先于指针,有几个原因:

For the why references should be preferred to pointers, there is several reasons:

  • 引用比函数体中的指针引入更少的语法噪音
  • 引用保存的信息比指针多,对编译器有用

引用的缺点主要是:

  • 它们打破了 C 的简单的按值传递规则,是什么让理解函数关于参数的行为(它们会被改变吗?)不太明显.您还需要函数原型来确定.但这并不比使用 C 时所需的多个指针级别更糟糕.
  • C 不支持它们,当您编写的代码应适用于 C 和 C++ 程序时,这可能会成为一个问题(但这不是最常见的情况).

在指针到指针的特定情况下,区别主要是简单,但使用引用可能也很容易删除两级指针,只传递一个引用而不是指向指针的指针.

In the specific case of pointer to pointer, the difference is mostly simplicity, but using reference it may also be easy to remove both levels of pointers and pass only one reference instead of a pointer to pointer.

这篇关于在 C++ 中传递指针参数,按值传递吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Returning a pointer of a local variable C++(返回局部变量 C++ 的指针)
Inline function linkage(内联函数联动)
Which is more efficient: Return a value vs. Pass by reference?(哪个更有效:返回值与通过引用传递?)
Why is std::function not equality comparable?(为什么 std::function 不具有可比性?)
C++ overload resolution(C++ 重载解析)
When to Overload the Comma Operator?(什么时候重载逗号运算符?)