[英]Does it make any sense to declare a static variable in a class' function where the object is static
Lets say my class lets say I have 可以说我的班级可以说我有
static classA myObject;
void classA::update(int elapsed)
{
static int sumElapsed = 0;
sumElapsed+= elapsed;
}
It seems that my questions is kind of hard to understand. 看来我的问题有点难以理解。 But if we say that myObject is a singleton of classA.
但是,如果说myObject是classA的单例。 Is there a difference between the local static int sumElapsed and a private member int sumElapsed of the classA, other than the scope in which they can get accessed.
除了可以访问它们的范围之外,classA的本地静态int sumElapsed和私有成员int sumElapsed之间是否有区别。
Sure. 当然。 For example in the singleton pattern.
例如在单例模式中。 There a reference (or pointer) to the static variable is also returned from a static method.
静态方法的引用(或指针)也从静态方法返回。
For an example see here: c++ Meyers singleton undefined reference 有关示例,请参见此处: c ++ Meyers单例未定义参考
By the way, if you are interested: Are Singletons really that bad? 顺便说一句,如果您有兴趣: Singletons真的那么糟糕吗?
如果您不希望覆盖sumElapsed,则可以,但是,将sumElapsed作为静态变量封装在classA中似乎更有意义。
Effectively, when you need some sort of a static member in a class template there aren't really good alternatives in the first place. 实际上,当您在类模板中需要某种静态成员时,首先并没有真正好的选择。 Also, if the members aren't trivial you probably want to put them into a function in the first place to have some level of control over the order of initialization.
另外,如果成员不是很简单的话,您可能首先想将它们放入函数中,以便对初始化顺序进行某种程度的控制。
In general, be aware that whether you put a static member into a class or into a function, it is still effectively implementing the Singleton anti-pattern ! 通常,请注意,无论您将静态成员放入类还是函数中,它仍然有效地实现了Singleton 反模式 !
Of course. 当然。 If
sumElapsed
isn't static, it will get overwritten every time the function is called; 如果
sumElapsed
不是静态的,则每次调用该函数时都会被覆盖; as it is, it won't be. 实际上,它不会。 The fact that
classA::update
is itself static is irrelevant; classA::update
本身是静态的事实无关紧要; just consider if it was a global function (eg in C). 只考虑它是否是一个全局函数(例如在C中)。
You should use a static class to hold methods that are not associated with a particular object. 您应该使用静态类来保存与特定对象无关的方法。 That being said, use a static class to hold only static members that cannot be instantiated by objects, and shouldn't be overwritten.
话虽这么说,使用静态类仅包含不能被对象实例化且不应被覆盖的静态成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.