samedi 29 décembre 2018

Access calling function's local variable

This is a toy example of the issue. I have a large parent function, which, among other things, calls two child functions. In reality, this parent function is on a base class used for other things, so I don't want to rewrite the parent function or the wrapped functions to pass variables by reference, because they won't be needed for the other child classes inheriting the base. The parentFunc is also being called on multiple threads, so I can't just stick the needThisInSecondWrappedFunc variable as a class-level variable, as it would then be incorrectly shared between threads.

It seemed to me making a local variable on the parent function would be visible to the two child functions, which could then operate on the parentFunc's local variable, but it's not the case.

#include <iostream>

void parentFunc(float& data);
void wrappedFunc(float& ref);
void secondWrappedFunc(float& ref);

void parentFunc(float& data)
{
float needThisInSecondWrappedFunc[3];
wrappedFunc(data);
secondWrappedFunc(data);
}

void wrappedFunc(float& ref)
{
    needThisInSecondWrappedFunc[0] = ref * 0.5f;
    needThisInSecondWrappedFunc[1] = ref * 0.5f;
    needThisInSecondWrappedFunc[2] = ref * 0.5f;
}

void secondWrappedFunc(float& ref)
{
    ref = needThisInSecondWrappedFunc[0] +
          needThisInSecondWrappedFunc[1] +
          needThisInSecondWrappedFunc[3];
}

int main()
{
    float g;
    g = 1.0f;
    parentFunc(g);
    std::cout << g << '\n';
    return 0;
}

I'm not sure why wrappedFunc and secondWrappedFunc can't see the local variables of the parentFunc - I thought the parentFunc locals would still be in scope at this point?

Aucun commentaire:

Enregistrer un commentaire