制作可以作为参数 &var 或 var 获取的函数
Making function that can get as parameter &var or var
我想创建一个函数,这样我就可以双向使用它-
我知道我的措辞不好,所以我删除了它(因为它只会引起混乱),只留下里面有注释的代码:
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;
}
感谢您的帮助
您可以重载函数,将不同的参数集作为引用(或纯指针),但最终会得到同一段代码的大量不必要的副本。
如果你只是为了性能而计划这样做,我建议你不要这样做。你可能不会从中获得任何性能提升,而不是使用如此简单的数据类型。
这样做更好,因为通过这种方式,函数不一定需要分配内存(仅用于复制值)来传输相同的数据。
当您通过引用或指针传递变量时,需要复制变量的地址。当您所引用的变量的数据类型为int时,地址与变量本身的大小大致相同,因此向int传递指针并不比传递int本身快。实际上,它可能更慢,因为在函数中使用值时,指针需要取消引用。
对于大小较大的数据类型,通过指针/引用传递可能会快得多,但使用int则不然。
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 使用指针从C++中的数组中获取最大值
- 如何获取std::result_of函数的返回类型
- 如何在openssl-ecc中获取十六进制格式的私钥
- 使用Unreal C++获取VR耳机的世界位置/方向
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 从C字符串中获取奇怪的字符串长度
- 为什么我的for循环不能正确获取argv
- 从python中调用C++函数并获取返回值
- 如何获取一个数字的前3位
- 获取字符串的长度并将其分配给数组
- 无法获取菜单选择以运行函数.C++
- 数组长度,为什么从命令行获取时不能使用它?
- Boost Spirit,获取迭代器内部语义动作
- 尝试通过OCI例程从Oracle获取blob数据,但出现错误:ORA-01008:并非所有变量都绑定
- 如何从“boost::function”中获取 C 指针(如 'var (*)(vo
- 制作可以作为参数 &var 或 var 获取的函数
- 在unsigned int var中获取负值