Static class in C++
In the header I declared
#ifndef SOUND_CORE
#define SOUND_CORE
static SoundEngine soundEngine;
...
but the constructor for SoundEngine gets called multiple times, how is it possible, when it's declared a开发者_如何学Pythons global static
I call it as
#include "SoundCore.h"
and use it directly
soundEngine.foo()
thank you
I would use extern
instead of static. That's what extern
is for.
In the header:
extern SoundEngine soundEngine;
In an accompanying source file:
SoundEngine soundEngine;
This will create one translation unit with the instance, and including the header will allow you to use it everywhere in your code.
// A.cpp
#include <iostream>
// other includes here
...
extern int hours; // this is declared globally in B.cpp
int foo()
{
hours = 1;
}
// B.cpp
#include <iostream>
// other includes here
...
int hours; // here we declare the object WITHOUT extern
extern void foo(); // extern is optional on this line
int main()
{
foo();
}
A copy of static variables declared in header files gets created for each translation unit where you include the header.
Never declare your static variables inside header files.
You could use a singleton object.
As others mentioned in the answers, static
variable in header file gets included in every file where the the header is included. If you want to still keep it static
and avoid multiple instantiations then wrap it in a struct
.
//SoundCore.h
struct Wrap {
static SoundEngine soundEngine;
};
Now define this variable in one of the .cpp
files.
//SoundCore.cpp
SoundEngine Wrap::soundEngine;
And use it simply as,
Wrap::soundEngine.foo();
If you include this header file in multiple files, your class will be instantiated for every inclusion. I think you better take a look at Singleton pattern, to get only 1 instance, i.e., just one constructor call.
As many other reserved words, static is a modifier that has different meanings according with the context.
In this case, you are creating an object of the class SoundEngine which is private in this module. This means that it is not visible from other modules.
However, you put this line in the header, so it is a private object in various modules. I guess that's the reason of the constructor being called multiple times.
精彩评论