Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
📘 Lesson  ·  Lesson 76

new and delete

Storage, Lifetime और Ownership

  1. Storage: suitable size/alignment के bytes मिलें।
  2. Lifetime: object construct होकर बाद में destroy हो।
  3. Ownership: कोई component exactly once cleanup की जिम्मेदारी ले।
int local=42;              // automatic, preferred
int* dynamic=new int{42}; // manual dynamic owner
delete dynamic;
dynamic=nullptr;

new allocation + initialization करता, delete destructor + deallocation। Pointer चाहिए इसलिए dynamic allocation जरूरी नहीं; pointer non-owning भी हो सकता है।

Scoped object/reference/container चुनें, जब तक lifetime को सच में dynamic रखने की requirement न हो।

Single Object new और delete

int* score=new int{95};
std::cout<<"Score: "<<*score<<'\n';
delete score;
score=nullptr;
Score: 95

Successful allocation path पर exactly one matching delete चाहिए। Delete के बाद pointer dangling; nullptr assignment केवल उसी variable को मदद करता है, copied aliases फिर भी dangling हैं। new int का value indeterminate, new int{} zero और new int{95} 95 initialize करता है।

Dynamic Arrays और Matching Forms

int* marks=new int[3]{72,88,91};
for(int i=0;i<3;++i) std::cout<<marks[i]<<' ';
delete[] marks;
72 88 91
AllocationRelease
new Tdelete p
new T[n]delete[] p

Mismatch, double delete, interior pointer delete या non-new storage delete undefined behavior है। Ordinary collection के लिए std::vector<int> marks{72,88,91}; लें—size और cleanup automatic। vector तथा dynamic memory पढ़ें।

Objects और Destruction

class Student{
 std::string name_;
public:
 explicit Student(std::string n):name_(std::move(n)){
  std::cout<<"Constructed: "<<name_<<'\n'; }
 ~Student(){std::cout<<"Destroyed: "<<name_<<'\n';}
 void print()const{std::cout<<"Student: "<<name_<<'\n';}
};
Student* s=new Student{"Aman"};
s->print();
delete s;
Constructed: Aman Student: Aman Destroyed: Aman

Construction पूरा होने के बाद pointer मिलता है। Delete पहले destructor, फिर storage deallocate करता है। Constructor throw हो तो new-expression obtained storage release करता है; members को RAII owner रखें। destructors देखें।

Failure और Advanced Forms

Throwing new

try{
 auto* data=new int[huge_count];
 delete[] data;
}catch(const std::bad_alloc&){ /* policy */ }

Ordinary failure सामान्यतः bad_alloc throw करता है। केवल meaningful recovery boundary पर catch करें।

Nothrow

int* p=new(std::nothrow) int{7};
if(!p){ /* failure */ } else delete p;

Nothrow allocation failure पर nullptr; object constructor के other exceptions फिर भी संभव।

Placement new

Supplied aligned storage में object construct करता है; ordinary delete नहीं लगती और explicit destruction/lifetime rules चाहिए। यह allocators जैसी expert infrastructure technique है, application default नहीं।

Ownership Rules

BugPrevention
LeakRAII owner
Double deleteUnique ownership
Use-after-freeClear lifetime
MismatchContainer/RAII
Ambiguous ownerOwner type/API में
Exception leakImmediate RAII acquisition
void process(const Student*);          // non-owner
void take(std::unique_ptr<Student>);  // transfer
Student& require(Student&);           // borrowed non-null

Raw pointer/reference normally non-owning view हो। एक raw pointer से दो independent smart owners कभी न बनाएं। Standard members होने पर Rule of Zero अपनाएं।

RAII और Smart Pointers

auto student=std::make_unique<Student>("Aman");
student->print();
// scope end पर automatic destruction
Constructed: Aman Student: Aman Destroyed: Aman
NeedPreferred
Scoped valueObject by value
Dynamic sequencevector/string
Exclusive ownerunique_ptr/make_unique
Real shared lifetimeshared_ptr/make_shared
Non-owning shared observationweak_ptr when needed

unique_ptr default dynamic owner है। shared_ptr केवल real shared graph में; cycles weak_ptr या ownership redesign से तोड़ें। Function केवल object use करता है तो reference लें, ownership pointer नहीं। smart pointers पढ़ें।

Mistakes और 100-Point Checklist

MistakeCorrection
Manual ordinary arrayvector/array/string
Early return leakImmediate RAII
new[] + deleteMatching form/remove pair
Two ownersOne owner, बाकी borrowers
shared_ptr defaultValue/unique ownership
Placement new business codeExpert infrastructure only
  1. Automatic object possible?
  2. Standard container possible?
  3. Owner type में visible?
  4. Unique ownership enough?
  5. Forms matched?
  6. Exceptions/returns safe?
  7. Borrow owner से shorter?
  8. Bounds explicit?
  9. Sanitizer tests?
  10. RAII internals के बाहर zero naked owning new/delete?
g++ -std=c++20 -Wall -Wextra -Wpedantic \
 -fsanitize=address,undefined app.cpp

Authoritative संदर्भ

Lifetime, matching और failure rules current working draft से verified हैं। Production guidance scoped objects, RAII containers और ownership types को naked new/delete पर prefer करती है।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

C++ में new और delete वास्तव में क्या करते हैं?
new-expression storage लेकर object initialize/construct करता और pointer देता है। Matching delete-expression destructor चलाकर corresponding deallocation function से storage release करता है।
new[] के साथ delete लगाने पर क्या होगा?
Forms match नहीं करतीं, इसलिए behavior undefined है। new/delete और new[]/delete[] pair करें। बेहतर है vector/string/RAII owner प्रयोग करें।
Null pointer को delete करना safe है?
हां, null pointer पर delete का कोई effect नहीं। लेकिन delete के बाद एक pointer को nullptr करने से दूसरे aliases safe नहीं हो जाते।
Allocation fail होने पर क्या होता है?
Ordinary throwing new सामान्यतः std::bad_alloc throw करता है। std::nothrow form failure पर nullptr देता है, इसलिए dereference से पहले check जरूरी है।
Modern C++ में raw new/delete कब लेना चाहिए?
Application code में बहुत कम। Automatic objects, containers और exclusive ownership में make_unique चुनें; केवल वास्तविक shared ownership में make_shared। Raw ownership low-level RAII abstraction के अंदर सीमित रखें।
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicBubble Sort आपकी प्रगति: 76 / 81 (94%) · Lesson 77 / 81 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें