How much work should be done in a constructor?

后端 未结 18 1139
离开以前
离开以前 2020-11-27 17:40

Should operations that could take some time be performed in a constructor or should the object be constructed and then initialised later.

For example when constructi

18条回答
  •  醉话见心
    2020-11-27 17:49

    RAII is the backbone of C++ resource management, so acquire the resources you need in the constructor, release them in the destructor.

    This is when you establish your class invariants. If it takes time, it takes time. The fewer "if X exists do Y" constructs you have, the simpler the rest of the class will be to design. Later, if profiling shows this to be a problem, consider optimizations like lazy initialization (acquiring resources when you first need them).

提交回复
热议问题