S
S
sddvxd2018-01-29 15:24:05
C++ / C#
sddvxd, 2018-01-29 15:24:05

What is the difference between declaring with new and without it?

In addition, the construction with new allows you to manually free the memory later

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mercury13, 2018-01-29
@sddvxd

POSITION IN MEMORY
Without new: static/global - in the data segment, local - on the stack. In the data segment, memory is allocated during compilation by linking, creating a stack frame is two processor commands.
With new: on the heap. Heap management is quite a difficult task, and if there are a lot of these new, the program can start to slow down.
LIFETIME
Without new: the object lives while execution is in the given block. When the block is exited, the destructor automatically fires.
With new: Destroy whenever we want.
NAME
Without new: the object is bound to its name.
With new: the object is unnamed (only the pointer has a name). Therefore, data structures of variable size are possible: dynamic arrays, linked lists, trees, and so on.
SIZE
Without new: given at compile time. That is, an array of 10 positions, and a point, more - only by recompilation.
With new: arbitrary.

R
res2001, 2018-01-29
@res2001

new allocates memory on the heap, while a definition without new allocates on the stack, with all its advantages and disadvantages. You need to understand when to define an object on the heap, and when on the stack.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question