Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does "Class myclass = Class()" waste resources?

I have a class:

class Cat {
   Cat();
   Tail longTail;
}

I am not sure about a proper way to write constructor for it. I don't want to make longTail a pointer for non-related reason.

Cat::Cat() : longTail(length) {...} 

That one doesn't fit because length is calculated in constructor, based on static members values at the moment of creation; (Poor practices upstream);


The question is

Cat::Cat() 
{
   int length;
   ...
   longTail = Tail(length);
}

How many times does creation and copying of Tail objects happen? They are CPU-expensive to both create and copy, and I need thousands of cats. It seems to me, this constructor first creates a default Tail object in longTail, after that it creates noname Tail object on the right of assignment, then runs operator= on longTail and noname Tail. Am I right? If yes, how should I write it instead to preserve CPU? I repeat: longTail needs a parameter, that is calculated in the constructor, and I can't edit Tail class.


1 Answers

In your second version your Tail-object will be default-initialized before the body of the constructor is run. In the body you create a second Tail-object and assign it to the first one.

To enable correct construction in the initializer-list, you could wrap the computation of the parameters in a static member-function (since, as you said, it only depends in static members):

class Cat {
public:
    Cat() : longTail(calculateLength()) {...} 

private:
    static int calculateLength() {}
like image 179
Björn Pollex Avatar answered Feb 03 '26 18:02

Björn Pollex