How to initialize static pointer

//How to initialize the static pointer?
// App.h
class App: public QObject{
public:
static ConnectManager * cm;
};

//App.cpp

ConnectManager App::cm = new ConnectManager(); //error

ConnectManager App::*cm = new ConnectManager(); //error too
//answer myself
ConnectManager *App::cm = new ConnectManager(); // ok
A static member of a class will exist no matter how many instances of the class there are, so in this case App::cm only goes out of scope after main() exits. So to avoid memory leaks you'd also need to delete the ConnectManager object created by App::cm on the heap with the new operator, something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

class ConnectManager{};
class App
{
    public:
    static ConnectManager * cm;
};
ConnectManager *App::cm = new ConnectManager();

int main()
{
    //....
    delete App::cm;
}


Alternatively you can use smart pointers:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <memory>

class ConnectManager{};
class App
{
    public:
    static std::shared_ptr<ConnectManager> cm;
};
std::shared_ptr<ConnectManager> App::cm (new ConnectManager());

int main()
{
    //...
    // no delete required
}

thx a lot ;)
Topic archived. No new replies allowed.