更改函数静态变量外部函数 [英] changing function static variable outside function

查看:75
本文介绍了更改函数静态变量外部函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

反正可以在函数外部更改函数静态变量

is there anyway to change a function static variable outside function

void foo()
{
   static int count =10;
}



是否可以在函数外部更改计数值?



is it possible to change the count value outside function?

推荐答案

是的,但是您不想这样做,否则将其视为静态的想法是完全没有意义的.如果要更改某些内容,然后更改其可见性,请不要解决问题.

因此,在这种情况下,您可以将函数转换为对象:
Yes, but you don''t want to, otherwise the idea of it being static is completely pointless. If you want to change something then change its visibility, don''t hack around the problem.

So in this case you could convert the function into an object:
class f
{
    public:
        f() : count_( 10 ) {}

        void operator()() { // do whatever foo did in here }

        int count_;
};

,然后将其设为静态.

要考虑的另一件事是……静电实际上只是伪装的全局变量.它们破坏了您程序的多线程功能(它们需要锁定),并且更难于推断程序的功能(它们可能使验证类的不变式更加困难).

将计数作为参数传递给该函数怎么样:

and make that a static.

Another thing to consider is... statics are really just globals in disguise. They damage the ability of your program to be multithreaded (they require locking) and it''s harder to reason about what a program does (they can make it harder to verify a class''s invariants).

How about just passing count as a parameter to the funtion:

void foo( int count )
{
    // do whatever foo did before
}

,那么您将获得用于多线程的可重入代码,并避免使用您想要的整个设置后称其为"模型.

then you get reentrant code for multi-threading, and avoid the whole "set it then call it" model you''re aiming for.


这篇关于更改函数静态变量外部函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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