C ++ is the best way to have a persistent object?

I am learning C ++ and I am trying to use my programming knowledge of other languages ​​to understand C ++, which seems to be very confusing to me. I am working on a basic socket program and trying to find a better way to handle creating a socket class so that I can read / write and only connect once.

In my other languages, I would create a static class of objects that would allow me to refer to it, if it had not been created, I would create a socket and connect. If it was created, I would just return it for links.

But the class cannot be a static class (at least not what I read), so I return to the next option that I know, which is Singleton.

So, I got something like

class Socket{
   static Socket* socket;
public:
   Socket& Get()
   {
      if (!socket) socket = new Socket;
      return *socket;
   }
};

/ . ? , . , , .

?

+4
3

- . , , . , , (, main()), , .

, , , : , - .

.


" " - , .

++ , , .

class StaticClass {
public:
  static Socket aStaticDataMember;
  static void aStaticFunction() {}
}

Socket StaticClass::aStaticDataMember = Socket(...);

int main() {
    StaticClass::aStaticFunction();
    StaticClass::aStaticDataMember.doWhatever();
}

// in a header
extern Socket globalVariable;
void globalFunction();

// in a cpp file
Socket globalVariable;
void globalFunction() {}

int main() {
  globalVariable.doWhatever();
  globalFunction();
}

Singleton

++, :

class SingletonClass {
public:
  void doWhatever() {}
private:
  // ... private members to implement singleton.
  // If you define any constructors they should be private

  friend SingletonClass &getSingletonClass() {
    static SingletonClass singleton; // thread safe in C++11
    return singleton;
  }
}

int main() {
  getSingletonClass().doWhatever();
}

:

class ComponentAThatUsesASocket {
private:
  Socket &socket;
public:
  ComponentAThatUsesASocket(Socket &s) : socket(s) {}

  void foo() {
    socket.doWhatever();
  }
}

int main() {
  Socket socket;

  ComponentAThatUsesASocket componentA(socket);
  componentA.doWhatever();

  ComponentB componentB(socket);
  componentB.doWhatever();
}
+1

:

class Socket{
public:
   static Socket& Get()
   {
      static Socket* socket = new Socket;
      return *socket;
   }
};

:

class Socket{
public:
   static Socket& Get()
   {
      static Socket socket;
      return socket;
   }
};

, , "" (. ). , ++ 11 , - (. ).

, , . . , (.. ).

+2

, , / . bad. , , , .

, , .

, " " , . ? , , ? , , , singleton/monostate. , - , , . , , .

+1
source

Source: https://habr.com/ru/post/1527213/


All Articles