Non-pointer class member: how good it is? [duplicate]

  • A+

This question already has an answer here:

I have the non pointer class member that I need to initialize in constructor:

class Alerter {  protected:   Timer timer;  public:   Alerter(int interval); }; 

and then

Alerter::Alerter(int interval) {     timer = createTimer(interval); } 

(simplified code just to demonstrate the problem).

I have some doubts and concerns that timer probably is first created with parameter-less constructor and later that instance is overwritten by the contents that the createTimer function returns.

How good is the approach? The possible answers could be:

  • The "empty timer" with parameter-less constructor is not actually created, as the compiler is smart enough to find we have never referenced it before overwriting the value.
  • The empty timer is created, but this is OK as well written code should support a cheap parameter-less constructor for throwaway instance.
  • Use you better pointers.

Which of these assumptions (or maybe something else) is the most correct?


timer is first default-constructed and then assigned. Of course you can make assumption about how cheap a Timer is to default-construct or about compiler optimization, but here you don't need this since can prevent default-construction by using an initializer list:

Alerter::Alerter(int interval) : timer(createTimer(interval)) { } 

This will work, unless your Timer class is copy-assignable but not copy-constructible, which would be weird.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: