From e54b9847001cc12dd9ac9e123264c2f6f563a074 Mon Sep 17 00:00:00 2001 From: Will Eccles Date: Wed, 27 Sep 2023 11:03:57 -0400 Subject: [PATCH] fix: RAII support for File class When a File object goes out of scope, its resources are not freed. This patch: - Adds a destructor to free this memory and close the file handle when the object is destroyed. - Deletes the copy constructor and copy assignment operator, as this class is not copyable (at least, not without more significant future work). - Adds move semantics. --- Fixes #66. --- src/SD.cpp | 31 +++++++++++++++++++++++++++++++ src/STM32SD.h | 9 +++++++++ 2 files changed, 40 insertions(+) diff --git a/src/SD.cpp b/src/SD.cpp index 4dd294e..4f47ecd 100644 --- a/src/SD.cpp +++ b/src/SD.cpp @@ -243,6 +243,37 @@ File::File(FRESULT result /* = FR_OK */) _res = result; } +File::File(File &&other) +{ + _name = other._name; + _fil = other._fil; + _dir = other._dir; + _res = other._res; + other._name = NULL; + other._fil = NULL; + other._dir = {}; +} + +File &File::operator=(File &&other) +{ + close(); + + _name = other._name; + _fil = other._fil; + _dir = other._dir; + _res = other._res; + other._name = NULL; + other._fil = NULL; + other._dir = {}; + + return *this; +} + +File::~File() +{ + close(); +} + /** List directory contents to Serial. * * \param[in] flags The inclusive OR of diff --git a/src/STM32SD.h b/src/STM32SD.h index 8033e2a..64b01cf 100644 --- a/src/STM32SD.h +++ b/src/STM32SD.h @@ -33,6 +33,15 @@ uint8_t const LS_R = 4; class File { public: File(FRESULT res = FR_OK); + + File(const File &) = delete; + File &operator=(const File &) = delete; + + File(File &&other); + File &operator=(File &&other); + + virtual ~File(); + virtual size_t write(uint8_t); virtual size_t write(const uint8_t *buf, size_t size); virtual size_t write(const char *buf, size_t size);