Lifetime of Objects
Lifetime of Objects
In C++, object lifetime refers to the period during which an object exists in memory and is valid for use. Understanding object lifetime is crucial for writing safe and correct C++ code. C++ defines well-defined rules for object creation, usage, and destruction.
- Automatic Storage Duration:Objects with automatic storage duration are created when a block of code is entered and destroyed when that block is exited. This includes local variables within functions or blocks.
#include <iostream>
void exampleFunction() {
int x = 10;
std::cout << x << std::endl;
}
int main() {
exampleFunction();
return 0;
}
- Dynamic Storage Duration (Dynamic Allocation): Objects with dynamic storage duration are created using dynamic memory allocation (e.g., ‘new’ operator) and must be explicitly deleted using ‘delete’ to avoid memory leaks.
#include <iostream>
int main() {
int* ptr = new int(42);
std::cout << *ptr << std::endl;
delete ptr;
return 0;
}
- Static Storage Duration: Objects with a static storage duration exist throughout the entire program execution. They are initialized before ‘main()’ is called and destroyed after ‘main()’ exits.
#include <iostream>
static int globalVar = 100;
int main() {
std::cout << globalVar << std::endl;
return 0;
}
- Thread Storage Duration: C++11 introduced thread-local storage for objects that are unique to each thread. These objects have a separate instances in each thread.
#include <iostream>
#include <thread>
thread_local int threadVar = 5;
void foo() {
threadVar += 1;
std::cout << "ThreadVar in foo: " << threadVar << std::endl;
}
int main() {
std::thread t1(foo);
t1.join();
std::cout << "ThreadVar in main: " << threadVar << std::endl;
return 0;
}
Understanding object lifetime helps in managing memory correctly, preventing use-after-free and memory leaks, and ensuring that objects are accessed only when they are valid. The C++ standard defines these concepts in detail, and adherence to these rules is essential for writing robust and reliable C++ code.