Lesson 20 of 24

Pointers, new/delete மற்றும் Smart PointersPointers, new/delete and Smart Pointers

11 min 35 XP

new heap-ல் memory ஒதுக்கும், delete விடுவிக்கும். delete மறந்தால் memory leak. Modern C++-ல் unique_ptr / shared_ptr பயன்படுத்துங்கள்: அவை தானாக விடுவிக்கும்.

new allocates heap memory and delete frees it; forget the delete and you leak memory. Modern C++ uses unique_ptr and shared_ptr, which free memory automatically.

Example: edit me and press Run

Output Loading C++ (first time takes a few seconds)
Press Run to see the result here.

new[] உடன் delete[]; new உடன் delete. கலந்தால் undefined behaviour. Smart pointers இந்தத் தவறுகளைத் தவிர்க்கும்.

Pair new[] with delete[] and new with delete; mixing them is undefined behaviour. Smart pointers avoid these mistakes entirely.

Challenge

+35 XP

Singly linked list: n மற்றும் n எண்களைப் படித்து ஒவ்வொன்றையும் list-ன் முன்பகுதியில் (head) சேர்த்து, பிறகு list-ஐ head முதல் print செய்யுங்கள். (Node-க்கு unique_ptr அல்லது new பயன்படுத்தலாம்.) Input: 4 1 2 3 4 Output: 4 3 2 1

Singly linked list: read n and n numbers, insert each at the head of the list, then print the list from the head. (Use unique_ptr or new for the nodes.) Input: 4 1 2 3 4 Output: 4 3 2 1

Output Loading C++ (first time takes a few seconds)
Press Run to see the result here.