静态与成员变量 [英] Static vs. member variable

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

问题描述

对于调试,我想在我的课上添加一些反变量。但是,这样做不会改变标题,导致很多重新编译。

For debugging, I would like to add some counter variables to my class. But it would be nice to do it without changing the header to cause much recompiling.

如果我正确地理解了这个关键字,以下两个代码片段将是完全相同的。假设当然只有一个实例。

If Ive understood the keyword correctly, the following two snippets would be quite identical. Assuming of course that there is only one instance.

class FooA
{
public:
    FooA() : count(0) {}
    ~FooA() {}

    void update()
    {
        ++count;
    }

private:
    int count;
};

vs。

class FooB
{
public:
    FooB() {}
    ~FooB() {}

    void update()
    {
        static int count = 0;
        ++count;
    }
};

FooA 中,可以在课堂内任何地方访问计数,

In FooA, count can be accessed anywhere within the class, and also bloats the header, as the variable should be removed when not needed anymore.

FooB 中,变量是仅在存在的一个函数中可见。以后容易删除我可以想到的唯一的缺点是FooB的计数在所有类的实例之间共享,但在我的情况下这不是问题。

In FooB, the variable is only visible within the one function where it exists. Easy to remove later. The only drawback I can think of is the fact that FooB's count is shared among all instances of the class, but thats not a problem in my case.


  • 这个关键字是否正确使用?我假设一旦计数 FooB 中创建,它将保持创建状态,并且不会重新初始化为每次更新的呼叫为零。

  • 我有什么其他的注意事项或者是头脑吗?

  • Is this correct use of the keyword? I assume that once count is created in FooB, it stays created and is not re-initialized to zero every call to update.
  • Are there any other caveats or headsup I should be aware of?

编辑:这将导致多线程环境中的问题,我明白我的代码库是单线程。

After being notified that this would cause problems in multithreaded environments, I clarify that my codebase is singlethreaded.

推荐答案

您对静态函数变量的假设是正确的。如果您从多个线程访问它,可能不正确。考虑使用InterlockedIncrement()。

Your assumptions about static function variables are correct. If you access this from multiple threads, it may not be correct. Consider using InterlockedIncrement().

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

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