Purpose of unique_ptr
std::unique_ptr is a smart pointer introduced in C++11 that manages dynamically allocated memory, ensuring proper resource deallocation and preventing memory leaks. Its key characteristic is exclusive ownership of the object it points to, meaning only one unique_ptr instance can own the same object at any given time. Once the unique_ptr is destroyed or goes out of scope, the memory it manages is automatically deallocated.
Uses:
- Resource Management: Automatically handles memory to prevent memory leaks caused by forgetting to release resources.
- Exclusive Ownership: Expresses exclusive ownership semantics to prevent multiple releases of resources.
- Safe Resource Transfer: Supports move semantics for safely transferring ownership, enabling safe return of resources from functions or passing local objects.
Example:
Assume a class Car where we want to create an instance in a function and return it without copying the object:
cpp#include <memory> class Car { public: Car() { std::cout << "Car created" << std::endl; } ~Car() { std::cout << "Car destroyed" << std::endl; } void drive() { std::cout << "Car driving" << std::endl; } }; std::unique_ptr<Car> createCar() { std::unique_ptr<Car> myCar = std::make_unique<Car>(); return myCar; // returns a unique_ptr with safe ownership transfer } int main() { std::unique_ptr<Car> car = createCar(); car->drive(); return 0; // car is automatically destroyed, memory is deallocated }
Purpose of array
std::array is a container type introduced in C++11 that wraps a raw array and provides a container-like interface. Compared to raw arrays, std::array offers safer and more convenient operations, with the size determined at compile time and stored on the stack.
Uses:
- Fixed-Size Array: Wraps a fixed-size array, providing type safety and additional member functions such as size(), begin(), and end().
- Performance: Offers nearly the same performance as raw arrays because data is stored on the stack, enabling fast access.
- Improved Semantics: Supports range-based for loops and functions from the algorithm library, making code more concise and maintainable.
Example:
Using std::array to store integers and iterate through them:
cpp#include <array> #include <iostream> int main() { std::array<int, 4> numbers = {1, 2, 3, 4}; for (int number : numbers) { std::cout << number << " "; } std::cout << std::endl; return 0; }
The above outlines several key uses of unique_ptr and array in modern C++ development, aimed at improving code safety, readability, and maintainability.