I would like some clarification on what happens when a class is instantiated on the stack.
When a C++ class is instantiated on the heap:
MyClass *myclass = new MyClass();
a pointer is created of type MyClass and the class is instantiated on the same line by “new MyClass();”. Stretching it out like this:
MyClass *myclass;
myclass = new MyClass();
If I’m not mistaken, a pointer is created on the 1st line and then memory is allocated for the instance on the 2nd line and a pointer to the address of the instance is assigned to myclass.
Does this mean that when a class is instantiated on the stack this way:
MyClass myclass = MyClass();
that it’s created twice?
“Stack” and “heap” have no definition in C++, memory is not required to be allocated anywhere.
With you example here:
You are initializing
myclassvia copy constructor to the temporary object.myclass(and the temporary) has automatic storage which you can consider being allocated on “the stack” if that makes you happy.Copy elision is allowed in this case, essentially optimizing it to
MyClass myClass, however note that it cannot always do this, such as when the copy constructor is private.Here is an example that you can test:
If the copy is elided you will see:
Otherwise (gcc option -fno-elide-constructors to prevent the elision happening):
Additionally, making the copy constructor private will give a compiler error.