From: Jérémie Galarneau Date: Wed, 29 Mar 2023 19:13:18 +0000 (-0400) Subject: file-desrcriptor: add assignment operator X-Git-Url: https://git.lttng.org./?a=commitdiff_plain;h=b37c485170fc29ed99e21a1c9e8a3bb3b24c184b;p=lttng-tools.git file-desrcriptor: add assignment operator Signed-off-by: Jérémie Galarneau Change-Id: I65ec468e0825801db47da6b1298d0bc09028415d --- diff --git a/src/common/file-descriptor.hpp b/src/common/file-descriptor.hpp index 8d6b64be4..0ddc2b91c 100644 --- a/src/common/file-descriptor.hpp +++ b/src/common/file-descriptor.hpp @@ -20,14 +20,23 @@ namespace lttng { */ class file_descriptor { public: - explicit file_descriptor(int raw_fd) noexcept : _raw_fd{raw_fd} + file_descriptor() + { + } + + explicit file_descriptor(int raw_fd) noexcept : _raw_fd{ raw_fd } { LTTNG_ASSERT(_is_valid_fd(_raw_fd)); } file_descriptor(const file_descriptor&) = delete; file_descriptor& operator=(const file_descriptor&) = delete; - file_descriptor& operator=(file_descriptor&&) = delete; + file_descriptor& operator=(file_descriptor&& other) + { + _cleanup(); + std::swap(_raw_fd, other._raw_fd); + return *this; + } file_descriptor(file_descriptor&& other) noexcept { @@ -36,14 +45,7 @@ public: ~file_descriptor() { - if (!_is_valid_fd(_raw_fd)) { - return; - } - - const auto ret = ::close(_raw_fd); - if (ret) { - PERROR("Failed to close file descriptor: fd=%i", _raw_fd); - } + _cleanup(); } int fd() const noexcept @@ -58,6 +60,20 @@ private: return fd >= 0; } + void _cleanup() + { + if (!_is_valid_fd(_raw_fd)) { + return; + } + + const auto ret = ::close(_raw_fd); + + _raw_fd = -1; + if (ret) { + PERROR("Failed to close file descriptor: fd=%i", _raw_fd); + } + } + int _raw_fd = -1; };