What's the difference between using * and using & in C++ functions?

时间:2015-05-08 09:53:58

标签: c++ function pointers reference function-pointers

I am trying to find out using the below code with sort an array in asscending order. And I find method 1,2,3,4 all get the same result:1234.

Which method is the best?

And when and why should should I use pointer /reference? Thanks you.

  1. Using & to call, and * in function parameter

  2. Just used * in function parameter

enter image description here

  1. Just used & in function parameter

    enter image description here

  2. nothing:

    -xs-

5 个答案:

答案 0 :(得分:1)

Your first two versions are identical. They both explicitly pass a pointer in to the function.

Your third version has the same semantics, but different syntax. References can be seen as pointers with nicer syntax.

Your fourth version doesn't actually swap the variables you pass in because you pass by value, so they are copied.

I would prefer the third version as it is clearer.

答案 1 :(得分:0)

Generally, references are more of a convenience thing. They allow the programmer to pass objects by reference without explicitly saying they want to do so

For example, this code

.ui-watermark

Is effectively equal to this code

private void showFragment() {
    Fragment fragment = JoinGroupFragment.newInstance();
    FragmentTransaction ft = getFragmentManager().beginTransaction()
            .replace(R.id.fragment_container, fragment, JOIN_GROUP_FRAGMENT_TAG);

    ft.commit();


    if (Build.VERSION.SDK_INT >= 21) {
        fragment.setEnterTransition(new Slide(Gravity.TOP));
        fragment.setExitTransition(new Slide(Gravity.BOTTOM));
    }

    ft.commit();
}

private void dismissFragment() {
    Fragment joinGroupFragment = getFragmentManager().findFragmentByTag(JOIN_GROUP_FRAGMENT_TAG);
    if (joinGroupFragment != null) {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.fragment_container, new Fragment());
        ft.commit();
    }
}

Both achieve the same result.

Also, in the case with classes/structs, references allow you to have direct access to class/struct members without having to type that stupid arrow (// C-style pointers some_func(int* x, int* y) { (*x)++; (*y)++; } ... int x = 5, y = 8; some_func(&x, &y); // x == 6 and y == 9 ):

// C++-style references
some_func(int& x, int& y)
{
    x++;
    y++;
}

...

int x = 5, y = 8;
some_func(x, y);
// x == 6 and y == 9

instead of

->

Please note that references used in this manner are a C++ feature only (there is no support for this in C). In C++ you have the choice of using either pointers or references, but IMHO references look 'cleaner' and require less typing (thus reducing the risk of RSI).

答案 2 :(得分:0)

I don't see a difference between [STAThread] static void Main() { Console.WriteLine(Test()); } [DllImport("Test.dll", EntryPoint = "Test", CallingConvention = CallingConvention.Cdecl,ExactSpelling = true)] public static extern Int32 Test(); and The program '[4712] Test.vshost.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'. . But in general:

  1. Passing pointers is passing an address to a variable. Then you modify something under this address using dereference i.e. 1..

  2. Same.

  3. Is passing via reference, it is basically equivalent of passing pointers with nicer syntax. There are of course some "minor" (from a beginner's point of view) differences, such as, you cannot make an empty reference (2.).

  4. Is passing by value, which does not operate on original operands but on their copies. At the function call, temporary copies of arguments are made. This means, you won't see changes to the argument outside of the function.

The general order of preference is:

  1. Use references, or *a references.
  2. If you need to make a copy of the object anyways, pass by value.
  3. Smart pointers.
  4. Pointers. Normal user should almost never need to resort to this.

Using references is preferred, because c++ prefers value-semantics. In other words, treating things like variables, i.e. not handlers/pointers. So when you pass a variable to a function, you type it naturally, even if you want to change it. You want to use the object, you pass the object. You don't care that under the hood it uses handlers.

Pointers are generally reserved for operations which deal with ownership of objects.

Separating pointers and references in such way makes it possible to express separate semantics with separate syntax. This makes code more readable.

答案 3 :(得分:0)

首先,我想指出你不应该使用

int a[]={1,2,3,4};

在您的代码中,因为即使您的交换功能不能正常工作,您的程序也将始终显示1234。因此,您应该使用类似

的内容
int a[]={2,4,1,3};

其次,方法1和方法2完全相同。根本没有区别。

第三,方法4不能正常工作,因为数组中的数据' a'还没有被修改过。发生这种情况是因为您已经通过值'传递了变量。而不是参考'。您将获得1234作为输出,因为这是您为阵列分配的内容。

最后,你唯一的选择是方法1和方法1之间的关系。和'方法3'。

我建议'方法3'因为与方法1相比,它使用起来更简单,更不容易产生混淆(和错误)。

答案 4 :(得分:0)

在某些情况下,通过引用传递允许编译器将基于寄存器的变量保存在被调用函数中的相同寄存器中(而不是将值存储在本地存储器中并将地址传递给该本地存储器到被调用函数)

相关问题