使用引用还是指针

使用引用还是指针

本文介绍了C ++函数参数:使用引用还是指针(然后取消引用)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给了我一些代码,其中一些参数是指针,然后将指针取消引用提供价值.我担心指针取消引用会花费周期,但是在查看之后以前的StackOverflow文章:取消引用指针?,也许没关系.

I was given some code in which some of the parameters are pointers, and then the pointers are dereferencedto provide values. I was concerned that the pointer dereferencing would cost cycles, but after looking ata previous StackOverflow article: How expensive is it to dereference a pointer?, perhaps it doesn't matter.

以下是一些示例:


bool MyFunc1(int * val1, int * val2)
{
    *val1 = 5;
    *val2 = 10;
    return true;
}

bool MyFunc2(int &val1, int &val2)
{
    val1 = 5;
    val2 = 10;
    return true;
}

就样式而言,我个人更喜欢传递引用,但是一个版本更好(就过程周期而言)?

I personally prefer the pass-by-reference as a matter of style, but is one version better(in terms of process cycles) than another?

推荐答案

如果参数可以为NULL(即在上述情况下为可选),则我的经验法则是通过指针传递,如果参数永远不应为NULL,则应进行引用.

My rule of thumb is to pass by pointer if the parameter can be NULL, ie optional in the cases above, and reference if the parameter should never be NULL.

这篇关于C ++函数参数:使用引用还是指针(然后取消引用)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 06:42