Fix potential bugs: improve exception handling, destructors, and cache management
This PR addresses several potential bugs and improves code robustness in the design patterns implementation:
Issues Fixed
1. Improper Exception Usage
Replaced deprecated std::exception() with more specific std::runtime_error with descriptive messages:
// Before
throw std::exception();
// After
throw std::runtime_error("Key already registered in factory");
This affects 6 locations across factory.h and memoize.h, providing better error diagnostics.
2. Destructors Throwing Exceptions
Fixed destructors in factory_registrator and memoize_registrator that could throw exceptions, violating C++ best practices:
// Before
~factory_registrator() {
_f.template unregister_type<U>();
}
// After
~factory_registrator() {
try {
_f.template unregister_type<U>();
} catch (...) {
// Destructors should not throw exceptions
}
}
3. Inconsistent Cache Management
Improved cache consistency in the memoize class by ensuring both _map_cache (weak_ptr) and _map_cache_shared (shared_ptr) are managed together:
// Before: only cleared shared cache
void clear() const {
_map_cache_shared.clear();
}
// After: clear both caches for consistency
void clear() const {
_map_cache.clear();
_map_cache_shared.clear();
}
4. Thread Safety Documentation
Added explicit warnings about thread safety requirements, as these classes use mutable containers without synchronization.
5. Build Configuration
Updated .gitignore to properly exclude node_modules/ and build artifacts.
Testing
The changes maintain backward compatibility and don't affect the public API. All existing tests should continue to pass as the fixes address potential runtime issues and improve error handling without changing functionality.
These improvements make the codebase more robust, follow C++ best practices, and provide better debugging information when issues occur.
💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.