Object Lifetime and Destruction Order in C++ with Examples
In C++, every object has a lifetime. The lifetime of an object refers to the period during which the object exists and its resources can be used according to the language rules. Understanding object lifetime and destruction order is important for learning constructors, destructors, memory management, inheritance, and resource management in C++.
C++ में प्रत्येक object का एक निश्चित lifetime होता है। Object Lifetime का अर्थ उस समय अवधि से है जिसमें object अस्तित्व में रहता है और उसके resources का उपयोग किया जा सकता है।
1. What Is Object Lifetime in C++?
Object lifetime is the period between the beginning and end of an object's existence.
An object is generally initialized when it is created. Its lifetime ends when it is destroyed according to the applicable C++ rules.
Example:
#include <iostream>using namespace std;class Student {public:Student() {cout << "Object Created" << endl;}~Student() {cout << "Object Destroyed" << endl;}};int main() {Student s1;cout << "Inside Main Function" << endl;return 0;}
Output:
Object CreatedInside Main FunctionObject Destroyed
Explanation:
The object
s1is created when execution reaches its declaration.Its constructor is called.
The statement inside
main()executes.When
main()ends, the local object is destroyed.Its destructor is called automatically.
हिन्दी में समझिए: जब s1 object बनाया जाता है, तो उसका constructor execute होता है। जैसे ही main() function समाप्त होता है, local object destroy हो जाता है और उसका destructor automatically execute होता है।
2. Lifetime of Local Objects
Local objects are declared inside a function or a block. Their lifetime is generally limited to the block in which they are created.
When the block ends, the objects with automatic storage duration are destroyed in the reverse order of their completed initialization.
Example:
#include <iostream>using namespace std;class Demo {public:Demo(int n) {cout << "Constructor: " << n << endl;}~Demo() {cout << "Destructor Called" << endl;}};int main() {Demo obj1(1);Demo obj2(2);cout << "End of Main" << endl;return 0;}
Output:
Constructor: 1Constructor: 2End of MainDestructor CalledDestructor Called
The constructor of obj1 executes first, followed by the constructor of obj2. At the end of the block, obj2 is destroyed first and then obj1.
हिन्दी में: Local objects का destruction उनके initialization के reverse order में होता है। पहले बनाया गया object अंत में destroy होता है।
3. Lifetime of Objects Inside Nested Blocks
An object declared inside an inner block is destroyed when that inner block ends. It does not wait for the outer function to finish.
Example:
#include <iostream>using namespace std;class Demo {public:Demo(string name) {cout << name << " Created" << endl;}~Demo() {cout << "Object Destroyed" << endl;}};int main() {Demo obj1("Outer Object");{Demo obj2("Inner Object");cout << "Inside Inner Block" << endl;}cout << "Back to Main Block" << endl;return 0;}
Output:
Outer Object CreatedInner Object CreatedInside Inner BlockObject DestroyedBack to Main BlockObject Destroyed
Explanation:
obj1is created in the outer block.obj2is created in the inner block.When the inner block ends,
obj2is destroyed.When
main()ends,obj1is destroyed.
हिन्दी में: Inner block समाप्त होते ही उसमें बनाया गया object destroy हो जाता है। Outer block का object तब तक मौजूद रहता है जब तक outer block समाप्त नहीं होता।
4. Lifetime of Global Objects
Global objects are declared outside all functions. Their storage duration is static, and they normally remain alive until program termination.
Their constructors are executed before main() begins, subject to the C++ initialization rules. Their destructors are called during normal program termination.
Example:
#include <iostream>using namespace std;class Demo {public:Demo() {cout << "Global Object Created" << endl;}~Demo() {cout << "Global Object Destroyed" << endl;}};Demo obj;int main() {cout << "Inside Main Function" << endl;return 0;}
Typical Output:
Global Object CreatedInside Main FunctionGlobal Object Destroyed
Explanation:
The global object
objis initialized beforemain()begins.The main function executes.
During normal program termination, the global object is destroyed.
हिन्दी में: Global object का lifetime सामान्यतः पूरे program के execution तक रहता है। इसका constructor main() से पहले और destructor normal program termination के दौरान execute होता है।
5. Lifetime of Static Local Objects
A static local object is declared inside a function using the static keyword.
Unlike an ordinary local object, it is initialized only once and remains alive until program termination.
Example:
#include <iostream>using namespace std;class Demo {public:Demo() {cout << "Static Object Created" << endl;}~Demo() {cout << "Static Object Destroyed" << endl;}};void display() {static Demo obj;cout << "Display Function Called" << endl;}int main() {display();display();cout << "End of Main" << endl;return 0;}
Output:
Static Object CreatedDisplay Function CalledDisplay Function CalledEnd of MainStatic Object Destroyed
Explanation:
The static object is initialized the first time
display()is called.The second function call does not create another object.
The object remains alive after
display()returns.Its destructor is called during normal program termination.
हिन्दी में: Static local object केवल पहली बार function call होने पर initialize होता है। Function समाप्त होने पर यह destroy नहीं होता, बल्कि program समाप्त होने तक मौजूद रहता है।
6. Lifetime of Dynamic Objects
Dynamic objects are created using the new operator. Their lifetime is controlled by dynamic allocation and deallocation, not simply by the scope of the pointer that stores their address.
The delete operator destroys a dynamically allocated object and releases its storage.
Example:
#include <iostream>using namespace std;class Demo {public:Demo() {cout << "Dynamic Object Created" << endl;}~Demo() {cout << "Dynamic Object Destroyed" << endl;}};int main() {Demo* ptr = new Demo();cout << "Using Dynamic Object" << endl;delete ptr;ptr = nullptr;return 0;}
Output:
Dynamic Object CreatedUsing Dynamic ObjectDynamic Object Destroyed
Explanation:
new Demo()creates an object dynamically.The pointer
ptrstores its address.The object remains alive even if the pointer variable goes out of scope, unless the object is destroyed separately.
delete ptrinvokes the destructor and releases the object's storage.Assigning
nullptrpreventsptrfrom retaining the old address.
हिन्दी में: Dynamic object को new से create किया जाता है। इसका lifetime pointer के scope पर निर्भर नहीं करता। delete operator से object destroy होता है और memory release होती है।
Note: If a dynamically allocated object is never deleted and no owning resource releases it, the program may have a memory leak. For modern C++, prefer smart pointers such as std::unique_ptr where appropriate.
7. Lifetime of Temporary Objects
Temporary objects are objects created for short-term use, often while evaluating expressions or passing values to functions.
In many common cases, a temporary object is destroyed at the end of the full-expression in which it was created.
Example:
#include <iostream>using namespace std;class Demo {public:Demo() {cout << "Temporary Object Created" << endl;}~Demo() {cout << "Temporary Object Destroyed" << endl;}};int main() {cout << "Before Temporary Object" << endl;Demo();cout << "After Temporary Object" << endl;return 0;}
Output:
Before Temporary ObjectTemporary Object CreatedTemporary Object DestroyedAfter Temporary Object
Explanation:
Demo()creates a temporary object.The temporary object is destroyed at the end of the statement.
The next statement executes after its destruction.
हिन्दी में: Temporary object सामान्यतः उस full-expression के समाप्त होने पर destroy हो जाता है जिसमें उसे बनाया गया है।
Lifetime Extension of Temporary Objects
In certain situations, the lifetime of a temporary object can be extended by binding it to a local reference.
Example:
#include <iostream>using namespace std;class Demo {public:Demo() {cout << "Object Created" << endl;}~Demo() {cout << "Object Destroyed" << endl;}};int main() {const Demo& ref = Demo();cout << "Object Is Still Alive" << endl;return 0;}
Output:
Object CreatedObject Is Still AliveObject Destroyed
Here, binding the temporary object to the local const lvalue reference extends its lifetime to the lifetime of the reference.
हिन्दी में: जब temporary object को local const lvalue reference से bind किया जाता है, तो उसका lifetime उस reference के lifetime तक बढ़ सकता है। Reference और temporary object की lifetime संबंधी कुछ विशेष नियम भी होते हैं।
8. Destruction Order of Class Members
When an object of a class is created, its data members are initialized in the order in which they are declared in the class, not in the order in which they appear in the constructor's member initializer list.
During destruction, members are destroyed in the reverse order of their declaration.
Example:
#include <iostream>using namespace std;class A {public:A() {cout << "A Created" << endl;}~A() {cout << "A Destroyed" << endl;}};class B {public:B() {cout << "B Created" << endl;}~B() {cout << "B Destroyed" << endl;}};class Test {A objA;B objB;public:Test() {cout << "Test Constructor" << endl;}~Test() {cout << "Test Destructor" << endl;}};int main() {Test obj;return 0;}
Output:
A CreatedB CreatedTest ConstructorTest DestructorB DestroyedA Destroyed
Explanation:
Member
objAis initialized first.Member
objBis initialized second.The constructor body executes.
The destructor body executes first.
Member
objBis destroyed.Member
objAis destroyed.
हिन्दी में: Class के data members declaration order में initialize होते हैं और reverse declaration order में destroy होते हैं। सबसे अंत में declared member सबसे पहले destroy होता है।
9. Object Lifetime in Inheritance
In inheritance, the base class constructor executes before the derived class constructor. During destruction, the derived class destructor executes before the base class destructor.
Example:
#include <iostream>using namespace std;class Base {public:Base() {cout << "Base Constructor" << endl;}virtual ~Base() {cout << "Base Destructor" << endl;}};class Derived : public Base {public:Derived() {cout << "Derived Constructor" << endl;}~Derived() override {cout << "Derived Destructor" << endl;}};int main() {Derived obj;return 0;}
Output:
Base ConstructorDerived ConstructorDerived DestructorBase Destructor
Explanation:
The Base Class constructor executes first.
The Derived Class constructor executes next.
During destruction, the Derived Class destructor executes first.
Finally, the Base Class destructor executes.
हिन्दी में: Inheritance में Base Class का constructor पहले और Derived Class का constructor बाद में execute होता है। Destruction के समय Derived Class का destructor पहले और Base Class का destructor बाद में execute होता है।
10. Managing Object Lifetime Using Smart Pointers
Modern C++ provides smart pointers to manage dynamically allocated objects automatically.
std::unique_ptr is an example of a smart pointer. It automatically destroys the object when the smart pointer goes out of scope.
Example:
#include <iostream>#include <memory>using namespace std;class Demo {public:Demo() {cout << "Object Created" << endl;}~Demo() {cout << "Object Destroyed" << endl;}};int main() {{unique_ptr<Demo> ptr = make_unique<Demo>();cout << "Inside Block" << endl;}cout << "Outside Block" << endl;return 0;}
Output:
Object CreatedInside BlockObject DestroyedOutside Block
Explanation:
make_unique<Demo>()creates a dynamically allocated object.unique_ptrmanages the object's ownership.When the inner block ends,
ptris destroyed.The managed object is automatically destroyed.
हिन्दी में: unique_ptr dynamically allocated object की ownership संभालता है। जैसे ही smart pointer का scope समाप्त होता है, वह अपने managed object को automatically destroy कर देता है। इससे manual delete की आवश्यकता कम होती है।
11. Object Lifetime and Storage Duration
Object lifetime and storage duration are related concepts, but they are not exactly the same.
| Storage Duration | Description | Common Example |
|---|---|---|
| Automatic | Storage is associated with block execution | Local variables |
| Static | Storage lasts for the duration of the program | Global and static variables |
| Dynamic | Storage is obtained through dynamic allocation | Objects created using new |
| Thread | Storage lasts for the lifetime of the thread | thread_local variables |
An object's lifetime is the period during which it exists as an object. Storage duration describes the duration of the storage associated with an entity.
हिन्दी में: Storage Duration यह बताता है कि किसी object के लिए memory कितनी अवधि तक उपलब्ध रहती है, जबकि Object Lifetime उस अवधि को बताता है जिसमें वह object C++ के नियमों के अनुसार अस्तित्व में रहता है।
12. Frequently Asked Questions (FAQs)
Q1. What is object lifetime in C++?
Object lifetime is the period during which an object exists and can be used according to C++ language rules.
Q2. When is a local object destroyed?
A local object with automatic storage duration is normally destroyed when its enclosing block ends.
Q3. When is a global object destroyed?
A global object is normally destroyed during program termination.
Q4. When is a static local object destroyed?
A static local object is destroyed during normal program termination, not when the function in which it is declared returns.
Q5. When is a dynamic object destroyed?
A dynamically allocated object is destroyed when it is properly deleted using delete, or when an owning resource such as a smart pointer releases it.
Q6. What is the destruction order of multiple local objects?
Objects are destroyed in the reverse order of their completed initialization within the same scope.
Q7. What is the destruction order of class data members?
Class data members are destroyed in the reverse order of their declaration.
Q8. What is the destruction order in inheritance?
The derived class destructor executes first, followed by the base class destructors.
Q9. What is RAII in C++?
RAII stands for Resource Acquisition Is Initialization. It is a C++ programming technique in which resource management is tied to object lifetime. Resources are acquired during object initialization and released automatically during destruction.
Q10. Why are smart pointers useful?
Smart pointers help manage dynamically allocated objects automatically and reduce the risk of memory leaks.
Object lifetime and destruction order are fundamental concepts in C++ programming. They help programmers understand when constructors and destructors execute and how resources are managed. By understanding local, global, static, dynamic, temporary, and class-member object lifetimes, programmers can write safer and more efficient C++ programs. Modern C++ features such as smart pointers and RAII make resource management easier and more reliable.
C++ में Object Lifetime और Destruction Order को समझना memory management और object-oriented programming के लिए आवश्यक है। Constructors, destructors, smart pointers और RAII की सहायता से सुरक्षित और efficient programs लिखे जा सकते हैं।
Comments
Post a Comment