For example this code:
#include <iostream>
using namespace std;
void foo(int* x){ cout << "X = " << *x << endl;}
int main()
{
int value = 5;
int *p = &value;
foo(p);
foo(&value);
return 0;
}
In the first call of function foo a copy of pointer p (x) is actually created within the function and deleted as soon as the function ends, right? In the second call of foo the address of variable value is taken and a pointer x is created with that address and is deleted as soon as the function ends, right? Which of these calls is cheaper in terms of stack memory consumption? Or are both the same thing?
They’re both similar. The first looks more expensive because you’re creating a pointer twice, once as a local variable (inside
main) and again as a function parameter (passed tofoo), however the “optimization” phase of the compiler will probably turn the first into the second (assuming that the only thing you do withpis pass it, and you don’t reuse it later inmain).