Is it OK for a class constructor to block forever?

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.


It's allowed. But like any other infinite loop, it must have observable side effects, otherwise you get undefined behavior.

Calling the networking functions counts as "observable side effects", so you're safe. This rule only bans loops that either do literally nothing, or just shuffle data around without interacting with the outside world.