Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make a variable inaccessible in a certain scope, possible?

Tags:

c++

scope

Is there a way to disable all access to a variable in a certain scope?

Its usage might be similar to this :-

int outerOnly=5; //primitive or class or struct, it can also be a field
outerOnly=4;  //ok
{//vvv The disable command may be in a block?
    disable outerOnly; //<--- I want some thing like this.
    outerOnly=4; //should compile error (may be assert fail?)
    int c=outerOnly;  //should compile error
}
outerOnly=4;  //ok

If the answer is no, is there any feature closest to this one?

It would be useful in a few situation of debugging.
Edit: For example, I know for sure that a certain scope (also too unique to be a function) should never access a single certain variable.

like image 547
javaLover Avatar asked Oct 15 '25 19:10

javaLover


2 Answers

Consider implementing something like this (perhaps with deleted copy constructors and assignment operators):

struct disable
{
private:
    disable(const disable&) = delete;
    disable& operator=(const disable&) = delete;
public:
    disable() {}
};

Then, placing

disable outerOnly;

inside the inner scope would result pretty much in the desired errors.

Keep in mind though, as @Cornstalks commented, that it may lead to shadowing-related compiler warnings (which, in turn, can usually be disabled on case by case basis).

like image 50
AlexD Avatar answered Oct 18 '25 11:10

AlexD


Is there a way to disable all access to a variable in a certain scope?

No, there is no such feature.

If the answer is no, is there any feature closest to this one?

Instead of a simple block, you could define and call a closure that doesn't capture the undesired variable:

int outerOnly;
int innerToo;
[&innerToo]()
{
    innerToo  = 42;        // ok
    outerOnly = 4;         // fails to compile
    int c     = outerOnly; // fails to compile
}();
like image 41
eerorika Avatar answered Oct 18 '25 13:10

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!