Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WinRT - no static constructors?

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

like image 959
Dean Chalk Avatar asked Jan 24 '26 20:01

Dean Chalk


2 Answers

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();
like image 184
Some programmer dude Avatar answered Jan 26 '26 11:01

Some programmer dude


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
    }
  }
};
like image 32
JoeG Avatar answered Jan 26 '26 12:01

JoeG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!