可以锁定变量以防止在c ++中更改它吗? [英] Can a variable be locked to prevent changes to it in c++?

查看:178
本文介绍了可以锁定变量以防止在c ++中更改它吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一个成员变量,在程序的某一点我想改变它,但我更喜欢锁定其他地方,以防止意外的更改。

I am using a member variable and at some point of the program I want to change it, but i prefer to "lock it" everywhere else to prevent unintended changes.

代码解释:

class myClass {
    int x;  // This should be prevented to being changed most of the time
    int y;  // Regular variable
    myclass() {x = 1;}
    void foo1 () {x++; y++;} // This can change x
    void foo2 () {x--; y--;} // This shouldn't be able to change x
                             // I want it to throw a compile error
};

问题是:它能以某种方式实现吗?比如永久const_cast?

The question is: Can it be achieved in some way? Something like permanent const_cast?

我知道我可以立即使用构造函数初始化列表和常量,但我需要稍后更改我的变量。

I know I could use constructor initialization list and constant right away, but i need to change my variable later.

推荐答案

好吧,我不喜欢的所有其他答案,所以这里是我的想法:隐藏变量。

Alright, all the other answers I dislike, so here's my idea: hide the variable.

#define READONLY(TYPE, VAR) const TYPE& VAR = this->VAR //C++03
#define READONLY(VARIABLE) const auto& VARIABLE = this->VARIABLE //C++11

class myClass {
    int x;  // This should be prevented to being changed most of the time
    int y;  // Regular variable
    myClass() :x(1), y(2) {}
    void foo1 () {// This can change x
        x++; 
        y++;
    } 
    void foo2 () {// This shouldn't be able to change x
        READONLY(x); //in this function, x is read-only
        x++; //error: increment of read-only variable 'x'
        y++;
    } 
};

还有方法绕过变量的锁定(例如 this - > x ),但对于这些情况无法执行。

There are still ways to bypass the locking of the variable (such as this->x), but nothing can be done for those situations.

这篇关于可以锁定变量以防止在c ++中更改它吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆