I'm currently authoring some WinRT custom controls in c++, and my compiler/intellisense is telling me that static constructors are not allowed.
I need to set up some static data, and I could use a private bool instance flag and on the first instantiation of my class I can create the static data etc.. (effectively achieving the same thing).
However, maybe I've missed something, as this seems a bit long-winded.
What is the canonical alternative approach to static construction in WinRT/c++
Thanks
You declare the static members inside the class, but you have to define them outside:
// In header file
class Foo
{
static int bar;
static int bar2;
static int init_bar3() { return 123; }
};
// In source file
int Foo::bar;
// Define and intiailize
int Foo::bar2 = 5;
// For more complicated initialization
int Foo::bar3 = Foo::init_bar3();
C++ doesn't support static constructors. Most of the time, you should use static initialisation as shown in Joachim Pileborg's answer. I'd advise you to adapt to that idiomatic C++ way of performing static initialisation rather than trying to write C++ in a C# style.
However, if you really need a C# style static constructor in C++, you can fake them:
class Foo {
public:
Foo() {
static_constructor();//call must appear in every constructor
}
Foo(Bar bar, Baz baz) {
static_constructor();//call must appear in every constructor
}
private:
static void static_constructor() {
static bool run = false;
if( !run ) {
run = true;
//your logic goes here
}
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With