Question

When passing arguments by reference in C++, how does it treat variables that are defined based on one of those references. For instance, I created a function MyFunc1 and then an alternate function MyFunc2 that tries to implement the same functionality. In the second, there is a y that is defined in terms of x. Is y also treated like a reference in terms of the amount of memory used?

int MyFunc1(const int &x, const int &a, const int &times_minus_one=1) {
    if (times_minus_one == 1) {
        return -x * a;
    } else {
        return x * a;
    }
}

and

int MyFunc2(const int &x, const int &a, const int &times_minus_one=1) {
    int y = x;
    if (times_minus_one == 1) {
        y = y * -1;
    }
    return y * a;
}
Was it helpful?

Solution

By the way you've defined y in MyFunc2, y is a copy of the original variable. Here the copy is being instantiated on the stack and will occupy sizeof(y) memory on the stack.

If for example you'd defined y as const auto& y = x; then y would be a reference which is simply the size of a pointer.

OTHER TIPS

The y in your code is just an integer to which you assign the value of x. It may or may not use any memory — the standard does not specify. As for memory footprint of references in general — they usually behave the same as pointers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top