In C++, when a function is called, a new stack frame is added to the call stack, containing its parameters and local variables (and other things). Does this also happen when an object constructor is called? If so, does this change when the constructor uses an initialization list? What is the structure of this stack frame? Does it contain the object's member variables (which must be in the heap after the execution of the constructor)?
You don't need to think constructor especially. It's just a kind of function - for example, This C++ code is
class Test
{
private:
int m_a;
public:
Test() : m_a(0) { puts("Test::Test()"); }
explicit Test(int i) : m_a(i) { puts("Test::Test(int)"); }
void f(char c) { puts("Test::f(char)"); }
~Test() { puts("Test::~Test()");
};
int main()
{
Test t1;
Test t2(3);
t1.f('a');
}
almost similar to
struct Test
{
int m_a;
};
void Test__ctor_0(Test *thiz) { thiz->m_a = 0; puts("Test::Test()"); }
void Test__ctor_1(Test *thiz, int i) { thiz->m_a = i; puts("Test::Test(int)"); }
void Test__f(Test *thiz, char c) { puts("Test::f(char)"); }
void Test__dtor_(Test *thiz) { puts("Test::~Test()"); }
int main()
{
struct Test t1;
Test__ctor_0(&t1);
struct Test t2;
Test__ctor_1(&t2, 3);
Test__f(&t1, 'a');
Test__dtor_(&t1);
Test__dtor_(&t2);
}
this C code.
Of course, the stack frame can be created when you call ctor, if it's not inlined or compiler optimizes call not to create stack frame to reduce the decrease of performance.
(In cdecl of x86, this pointer is sent through ecx register, unlike other parameter. So if the constructor don't use any local variables and don't have any additional parameters, stack frame could be not created.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With