new and delete
Storage, Lifetime और Ownership
- Storage: suitable size/alignment के bytes मिलें।
- Lifetime: object construct होकर बाद में destroy हो।
- 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 भी हो सकता है।
Single Object new और delete
int* score=new int{95};
std::cout<<"Score: "<<*score<<'\n';
delete score;
score=nullptr;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;| Allocation | Release |
|---|---|
| new T | delete 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;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
| Bug | Prevention |
|---|---|
| Leak | RAII owner |
| Double delete | Unique ownership |
| Use-after-free | Clear lifetime |
| Mismatch | Container/RAII |
| Ambiguous owner | Owner type/API में |
| Exception leak | Immediate RAII acquisition |
void process(const Student*); // non-owner
void take(std::unique_ptr<Student>); // transfer
Student& require(Student&); // borrowed non-nullRaw 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| Need | Preferred |
|---|---|
| Scoped value | Object by value |
| Dynamic sequence | vector/string |
| Exclusive owner | unique_ptr/make_unique |
| Real shared lifetime | shared_ptr/make_shared |
| Non-owning shared observation | weak_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
| Mistake | Correction |
|---|---|
| Manual ordinary array | vector/array/string |
| Early return leak | Immediate RAII |
| new[] + delete | Matching form/remove pair |
| Two owners | One owner, बाकी borrowers |
| shared_ptr default | Value/unique ownership |
| Placement new business code | Expert infrastructure only |
- Automatic object possible?
- Standard container possible?
- Owner type में visible?
- Unique ownership enough?
- Forms matched?
- Exceptions/returns safe?
- Borrow owner से shorter?
- Bounds explicit?
- Sanitizer tests?
- RAII internals के बाहर zero naked owning new/delete?
g++ -std=c++20 -Wall -Wextra -Wpedantic \
-fsanitize=address,undefined app.cppAuthoritative संदर्भ
Lifetime, matching और failure rules current working draft से verified हैं। Production guidance scoped objects, RAII containers और ownership types को naked new/delete पर prefer करती है।
