What (not) to do in a constructor

后端 未结 13 1714
悲&欢浪女
悲&欢浪女 2020-12-12 17:33

I want to ask you for your best practices regarding constructors in C++. I am not quite sure what I should do in a constructor and what not.

Should I only use it for

13条回答
  •  醉话见心
    2020-12-12 17:40

    From The C++ Programming Language:

    The use of functions such as init() to provide initialization for class objects is inelegant and errorprone. Because it is nowhere stated that an object must be initialized, a programmer can forget to do so – or do so twice (often with equally disastrous results). A better approach is to allow the programmer to declare a function with the explicit purpose of initializing objects. Because such a function constructs values of a given type, it is called a constructor.

    I usually consider the following rule when designing a class: I must be able to use any method of the class safely after the constructor has executed. Safe here means you could always throw exceptions if the object's init() method has not been called, but I prefer to have something that is actually usable.

    For instance, class std::string might not allocate any memory when you use the default constructor because most methods (i.e. begin() and end()) would work correctly if both return null pointers, and c_str() does not necessarily return the current buffer for other design reasons, therefore it has to be prepared to allocate memory at any time. Not allocating memory in this case still leads to a perfectly usable string instance.

    Conversely, use of RAII in scoped guards for mutex locks is an example of a constructor that may execute for an arbitrarily long time (until the lock's owner releases it) yet is still commonly accepted as good practice.

    In any case, lazy initialization may be done in safer ways than using an init() method. One way is to use some intermediate class that captures all parameters to the constructor. Another is to use the builder pattern.

提交回复
热议问题