Skip to content

Commit

Permalink
fix: RAII support for File class
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
willeccles committed Sep 27, 2023
1 parent e20b7f3 commit e54b984
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/SD.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions src/STM32SD.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit e54b984

Please sign in to comment.