Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
81 views
in Technique[技术] by (71.8m points)

c++ - 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...)

question from:https://stackoverflow.com/questions/64727165/is-it-ok-for-a-class-constructor-to-block-forever

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...