2

I recently discovered that local class cannot access Auto variables of enclosing function as they might contain invalid reference to local variable. For Example

struct Helper {
    virtual int getLocal() = 0;
};

Helper* nutshell(){
    int local = 123;
    struct Internal : public Helper {
        int i = INT16_MAX; // Unnecessary
        int getLocal(){ return local; }
    };
    return new Internal();
};

The above code is disaster because getLocal has invalid reference to local. A solution for this could be making local static or enum, But what's interesting for me is that making it a const is also a possible way.

struct Helper {
    virtual int getLocal() = 0;
};

Helper* nutshell(){
    const int local = 123;
    struct Internal : public Helper {
        int i = INT16_MAX; // Unnecessary
        int getLocal(){ return local; }
    };
    return new Internal();
};

My question is why is that, Why local class can access const variable?

Isn't a const qualified variable a Auto variable?

vector X
  • 89
  • 7
  • "Isn't a `const` qualified variable a Auto variable?" - Answer: No it isn't. – paladin Oct 11 '21 at 06:41
  • 1
    @paladin So, const variable doesn't has automatic storage duration? – vector X Oct 11 '21 at 06:43
  • This depends on the compiler and the code. (Many compiler try to "optimize" `const` "variables", aka getting rid of them entirely.) – paladin Oct 11 '21 at 06:49
  • perhaps this description helps you to understand it. https://stackoverflow.com/questions/15859643/which-memory-area-is-a-const-object-in-in-c – Igor Oct 11 '21 at 07:06
  • Because `const` is, err, `const`, so actually the compiler can copy the value into the local class, without having to worry about the enclosing stack frame disappearing. It can't do that with variables. – user207421 Oct 11 '21 at 07:24

0 Answers0