传递指针参数,传递C ++中的值? [英] Is passing pointer argument, pass by value in C++?

查看:119
本文介绍了传递指针参数,传递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.

如果你想反映对指针到外部指针的改变(使它指向别的东西)你需要两个间接层次(指向指针的指针)。当调用函数时,通过在指针名称前加一个& 来完成。

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和
  • they break the simple pass-by-value rule of C, what makes understanding the behavior of a function regarding of parameters (will they be changed ?) less obvious. You also need function prototype to be sure. But that is not really worse than the multiple pointer levels necessary when using C.
  • they are not supported by C, that can be a problem when you write code that should work with both C and C++ programs (but that's not the most usual case).

在指向指针的特定情况下,区别主要是简单,但是使用引用也可以容易地去除两个级别的指针并且仅传递一个引用而不是指向指针的指针。

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 ++中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆