Search code examples
c++multithreadingconstructorinfinite-loop

Is it OK for a class constructor to block forever?


Let's say I have an object that provides some sort of functionality in an infinite loop.

Is is acceptable to just put the infinite loop in the constructor?

Example:

class Server {
    public:
    Server() {
        for(;;) {
            //...
        }
    }
};

Or is there an inherent initialization problem in C++ if the constructor never completes?

(The idea is that to run a server you just say Server server;, possibly in a thread somewhere...)


Solution

  • It's not wrong per standard, it's just a bad design.

    Constructors don't usually block. Their purpose is to take a raw chunk of memory, and transform it into a valid C++ object. Destructors do the opposite: they take valid C++ objects and turn them back into raw chunks of memory.

    If your constructor blocks forever (emphasis on forever), it does something different than just turn a chunk of memory into an object. It's ok to block for a short time (a mutex is a perfect example of it), if this serves the construction of the object. In your case, it looks like your constructor is accepting and serving clients. This is not turning memory into objects.

    I suggest you split the constructor into a "real" constructor that builds a server object and another start method that serves clients (by starting an event loop).

    ps: In some cases you have to execute the functionality/logic of the object separately from the constructor, for example if your class inherit from std::enable_shared_from_this.