From c2927ce6f703bd8c050380049678d7bcee222bbc Mon Sep 17 00:00:00 2001 From: Veloman Yunkan Date: Sun, 28 Nov 2021 18:01:57 +0400 Subject: [PATCH] Library got a yet unused mutex Introducing a mutex in `Library` necessitates manually implementing the move constructor and assignment operator. It's better to still delegate that work to the compiler to eliminate any possibility of bugs when new data members are added to `Library`. The trick is to move the data into an auxiliary class `LibraryBase` and derive `Library` from it. --- include/library.h | 25 ++++++++++++++++++++++--- src/library.cpp | 28 +++++++++++++++++++++++----- 2 files changed, 45 insertions(+), 8 deletions(-) diff --git a/include/library.h b/include/library.h index 7211a843f..046329742 100644 --- a/include/library.h +++ b/include/library.h @@ -24,6 +24,7 @@ #include #include #include +#include #include #include "book.h" @@ -139,12 +140,14 @@ private: // functions bool accept(const Book& book) const; }; - /** - * A Library store several books. + * This class is not part of the libkiwix API. Its only purpose is + * to simplify the implementation of the Library's move operations + * and avoid bugs should new data members be added to Library. */ -class Library +class LibraryBase { +protected: // data std::map m_books; std::map> m_readers; std::map> m_archives; @@ -152,6 +155,22 @@ class Library class BookDB; std::unique_ptr m_bookDB; +protected: // functions + LibraryBase(); + ~LibraryBase(); + + LibraryBase(LibraryBase&& ); + LibraryBase& operator=(LibraryBase&& ); +}; + +/** + * A Library store several books. + */ +class Library : private LibraryBase +{ + // all data fields must be added in LibraryBase + mutable std::mutex m_mutex; + public: typedef std::vector BookIdCollection; typedef std::map AttributeCounts; diff --git a/src/library.cpp b/src/library.cpp index e7afad696..616e004b1 100644 --- a/src/library.cpp +++ b/src/library.cpp @@ -58,21 +58,39 @@ bool booksReferToTheSameArchive(const Book& book1, const Book& book2) } // unnamed namespace -class Library::BookDB : public Xapian::WritableDatabase +class LibraryBase::BookDB : public Xapian::WritableDatabase { public: BookDB() : Xapian::WritableDatabase("", Xapian::DB_BACKEND_INMEMORY) {} }; -/* Constructor */ -Library::Library() +LibraryBase::LibraryBase() : m_bookDB(new BookDB) { } -Library::Library(Library&& ) = default; +LibraryBase::~LibraryBase() +{ +} -Library& Library::operator=(Library&& ) = default; +LibraryBase::LibraryBase(LibraryBase&& ) = default; +LibraryBase& LibraryBase::operator=(LibraryBase&& ) = default; + +/* Constructor */ +Library::Library() +{ +} + +Library::Library(Library&& other) + : LibraryBase(std::move(other)) +{ +} + +Library& Library::operator=(Library&& other) +{ + LibraryBase::operator=(std::move(other)); + return *this; +} /* Destructor */ Library::~Library()