What (not) to do in a constructor

后端 未结 13 1718
悲&欢浪女
悲&欢浪女 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:53

    I think the most important thing is a bit of common sense! There's lots of talk about do's and dont's - all well and good, but the key point to consider is how your object will be used. For example,

    1. how many instances of this object will be created? (are they held in containers for example?)
    2. how often are they created and destroyed? (loops?)
    3. how big is it?

    If this object is a single instance, that is constructed at the start and the construction is not in the critical path - why not do the heavy work in the constructor (as long as you use exceptions appropriately, it may even make more sense)? If on the other hand, it's a very light weight object that is created and destroyed in a loop for a short period of time - try do as little as possible (aside from initializing the members, for example) (functors are a very good example of this...)

    There are advantages to having a two phase load (or whatever), but main disadvantage is forgetting to call it - how many of us have done that?? :)

    So, my tuppence is, don't stick to a hard and fast rule, look carefully at how your object is to be used, and then design it to suit!

提交回复
热议问题