Safe Memory Practices
Memory Management Strategies
Implementing safe memory practices is crucial for developing robust and reliable C++ applications.
Smart Pointer Usage
graph TD
A[Smart Pointers] --> B[unique_ptr]
A --> C[shared_ptr]
A --> D[weak_ptr]
Unique Pointer Example
#include <memory>
#include <iostream>
class Resource {
public:
Resource() { std::cout << "Resource Created" << std::endl; }
~Resource() { std::cout << "Resource Destroyed" << std::endl; }
};
void safeMemoryManagement() {
// Automatic memory management
std::unique_ptr<Resource> uniqueResource =
std::make_unique<Resource>();
// No manual delete required
}
RAII (Resource Acquisition Is Initialization)
class FileHandler {
private:
FILE* file;
public:
FileHandler(const char* filename) {
file = fopen(filename, "r");
}
~FileHandler() {
if (file) {
fclose(file);
}
}
};
Memory Management Techniques
Technique |
Description |
Benefit |
Smart Pointers |
Automatic memory management |
Prevents memory leaks |
RAII |
Resource management through object lifecycle |
Ensures proper resource release |
std::vector |
Dynamic array with automatic memory management |
Safe and flexible container |
Bounds Checking and Safe Alternatives
#include <vector>
#include <array>
void safeContainerUsage() {
// Safer than raw arrays
std::vector<int> dynamicArray = {1, 2, 3, 4, 5};
// Compile-time fixed size
std::array<int, 5> staticArray = {1, 2, 3, 4, 5};
// Bounds-checked access
try {
int value = dynamicArray.at(10); // Throws exception if out of bounds
} catch (const std::out_of_range& e) {
std::cerr << "Out of range access" << std::endl;
}
}
Memory Allocation Best Practices
- Prefer stack allocation when possible
- Use smart pointers for heap allocation
- Implement RAII principles
- Avoid manual memory management
- Use standard library containers
Advanced Memory Management
#include <memory>
class ComplexResource {
public:
// Custom deleter example
static void customDeleter(int* ptr) {
std::cout << "Custom deletion" << std::endl;
delete ptr;
}
void demonstrateCustomDeleter() {
// Using custom deleter with unique_ptr
std::unique_ptr<int, decltype(&customDeleter)>
customResource(new int(42), customDeleter);
}
};
Key Recommendations
- Minimize raw pointer usage
- Leverage standard library smart pointers
- Implement RAII for resource management
- Use containers with built-in memory management
At LabEx, we emphasize these safe memory practices to help developers write more reliable and efficient C++ code.