I’m new to c++.
I’ve got a Rectangle class. When I create a Rectangle object like this:
Rectangle R1(10,10,90,20);
- Does R1 sit on the heap or stack?
- If I were to create it using the
newoperator, would only then it be on the heap?
(In general what would be the correct way to create an object in c++?)
To my understanding, if I create it without new the object sits on the stack and does not need to be deleted at the end of its life time. And if do create it with new
Rectangle* R = new Rectangle(1,1,1,1);
it will be placed on the heap and would need to be de-allocated using delete.
This creates a variable with “automatic” duration. It is automatically destroyed when the code flow exits the scope. If it’s not in a function, that means when the execution of your code completes. Usually (but not always) it sits on some sort of stack.
This part is confusing: The variable
Ris a pointer with automatic duration (like above). It points at anRectanglewith “dynamic” duration. Usually (but not always) the dynamic object sits on some sort of heap. The rectangle is destroyed only when you explicitly destroy it withdelete R;. This means if the function ends and there is no other copy ofR, it becomes impossible to delete, and will remain in memory until your program ends. This is called a memory leak.In C++, dynamic memory is best handled with a smart pointer, such as
std::unique_ptr, so that you can’t accidentally forget to delete it, even if the code is crashing.