This question may turn out to be more about CPUs/memory than the C++ language itself.
I have a class B
provided below.
class B {
public:
B(int num): num_(num), a(num_){}
private:
int num_;
A a;
};
In the constructor of B
, the object a
is initialized with num_
rather than num
. I could instead have written this class B_Alternative
.
class B_Alternative {
public:
B_Alternative(int num) : num_(num), a(num) {}
private:
int num_;
A a;
};
Which is faster? My understanding is that the answer may depend on where B
is stored. If B
is on the stack, then the compiler will likely retrieve num_
from B
directly and there is no speed loss. If B
is on the heap, then a stack frame will need to be made to construct a
, and a copy of num_
will be moved to the stack to run A
's constructor. Then num_
will be moved back to the heap in the position of a
. This will result in the constructor of B
being slower than the constructor of B_Alternative
regardless of where B_Alternative
is stored.
An example A
is included below. This is just an example.
class A {
public:
A(int num) : num_(num) {}
private:
int num_;
};