问题
What exactly is happening in the code below.
#include<iostream.h>
class Demo
{
public :
Demo()
{
cout<<"\nIn Demo const";
}
~Demo()
{
cout<<"\nin demo dest";
}
};
void main() {
Demo();
}
Demo() simply calls the constructor and destructor. Is a object being created in this process? And thus is the memory being allocated?
回答1:
You're not explicitly calling the constructor, instead this code creates a temporary unnamed object with type Demo, which is destroyed immediately after ;.
Yes, memory is allocated (automatically, on the stack) for this temp object and it's freed (again automatically) after ;. Meanwhile, the constructor and destructor are called, as expected.
回答2:
Yes, memory is allocated but on the stack, and Demo() is creating a temporary object which gets destructed automatically.
来源:https://stackoverflow.com/questions/18892035/calling-a-constructor-without-creating-object