制作可以作为参数& var或var的函数

时间:2016-03-22 21:28:29

标签: c++ function variables pointers

我想创建一个函数,以便我可以两种方式使用它 -

我知道我的措辞不好所以我删除它(因为它只会导致混淆)并且只留下带有注释的代码:

int CalculationFunc(int i1, int i2, int i3, int i4, int i5) {
    /* Some calculation done here */
    return (i2*i3)+i5-i2+i4; /* <- this is not good example.. the calculation will be based also on
                             on values that are changing from time to time.. */
}

int main() {
// Situation 1:
    /* In this situation I didn't initialized any parameter before because I didn't
    need to.. all I need is to call to the functions with predefined values */
    int iAnswer1 = CalculationFunc(1, 2, 3, 4, 5);
    /*^ Everything is fine in this case - I Allocate memory only once*/

// ----------------------------------------------------------
// Situation 2:

    int iVal1 = 0, iVal3 = 0, iVal5 = 0; // <-- Memory is allocated 
    /* ... something done here so the values of are not constant ...
    (The code for this is not written) */


    /*In this situation something different: some values that I going to pass to the
    function are not predefined, and they are outcome of some pre-calculation done before,
    so there is allocated memory for them. If I call to the functions with these variables: */
    int iAnswer2 = CalculationFunc(iVal1, 6, iVal3, 2, iVal5);
    /* ^ There is not really a "real-world" problem here. the problem is that what happening
    In low-level is this:
        a) allocate memory for iVal1 , iVal3 , iVal5
        b) copy value of iVal1 to the allocated memory (and the same for iVal3 and iVal5)
        c) use the allocated memory..

    This is not efficient. What I want to do is to pass pointers for iVal1, iVal3, iVal5
    And the function will automatically get the data using the pointers. 
    So there will not be steps a and b.

    This is how I want to call it:
        CalculationFunc(&iVal1, 6, &iVal3, 2, &iVal5)
    */


    return 0;
}

感谢帮助者!

1 个答案:

答案 0 :(得分:0)

您可以重载函数以将不同的参数集作为引用(或普通指针),但最终会得到同一段代码的大量不必要的副本。

如果你打算为了表现而这样做,我建议你不要这样做。你可能不会从中获得任何性能提升,而不是这种简单的数据类型。

  

这样做更好,因为这种方式函数不一定需要分配内存(仅用于复制值)来传输相同的数据。

当您通过引用或指针传递变量时,需要复制变量的地址。当你引用的变量的数据类型是int时,地址与变量本身大小相同,因此将指针传递给int并不比传递int本身快。实际上,它可能更慢,因为当在函数中使用该值时,需要取消引用指针。

对于通过指针/引用传递较大大小的数据类型可能会明显更快,但不会使用整数。