What are the differences of these lines? Both work. When is one case or another used?
Class* obj = new Class();Class obj;
What are the differences of these lines? Both work. When is one case or another used?
Class* obj = new Class();
Class obj;
In the first case, you create an object in the heap. You allocate the memory yourself; you yourself must delete it with the delete operator. Access to the fields and methods of the object occurs through the arrow -> .
In the second case, an object is created on the stack; it will be automatically given when its scope is complete. The object is accessed through a point .
The first method allows you to determine any lifetime of the object, use it in different parts of the program. But it is also fraught with consequences, since the programmer may forget to delete the object from memory. Therefore, without the need for an object should not create a heap.
I’ll clarify that for the second object, the destructor is automatically called when the control flow leaves the function. In principle, in 90% percent, you can write without new-delete.
Source: https://ru.stackoverflow.com/questions/523133/
All Articles