1. 程式人生 > >Modern C++ Course [Lecture 7] {Pointers, const with pointers, Stack and Heap, Memory leaks, Dangling pointers}

Modern C++ Course [Lecture 7] {Pointers, const with pointers, Stack and Heap, Memory leaks, Dangling pointers}

mov sed info variable exp eve different var delet

技術分享圖片

技術分享圖片

https://en.cppreference.com/w/cpp/language/range-for

技術分享圖片

技術分享圖片

技術分享圖片

every object has a pointer to itsleft.

技術分享圖片

技術分享圖片

技術分享圖片

stack operations are very quick

it‘s computationally expensive to search variables in a stack, when the scopes and functions are very large.

So, keep your scope and func small.

An example:

技術分享圖片

then we create a new scope

技術分享圖片

技術分享圖片

技術分享圖片

end of scope, and the scope does 2x pop, and remove everything from the first parenthesis

(beauty of C++ is that it manages its memory based on scopes)

the problem now is that prt loses its value

技術分享圖片

技術分享圖片

heap is much more complicated than stack

heap usually has much larger volume than stack

memory management is not automatically done.

技術分享圖片

?????

技術分享圖片

技術分享圖片

技術分享圖片

技術分享圖片

eg, first we assign ptr 1 and 2 to two different velues

技術分享圖片

then we assign ptr 2 to the address of the upper variable

技術分享圖片

the system thinks we might use the bottom variable, but we have lost access to it, and we can‘t remove it by delete some_ptr

技術分享圖片

we tried to delete some memory twice.

技術分享圖片

技術分享圖片

in line 10, every time we allocate a new data, system creates a new ptr to it. we can‘t use line 16 to free the memory

技術分享圖片

技術分享圖片

技術分享圖片

技術分享圖片

技術分享圖片

this is the way before c++11

技術分享圖片

技術分享圖片

技術分享圖片

Modern C++ Course [Lecture 7] {Pointers, const with pointers, Stack and Heap, Memory leaks, Dangling pointers}