From 14848875bf070c18f614568584a9fb54c33d95be Mon Sep 17 00:00:00 2001 From: vtta <41831480+vtta@users.noreply.github.com> Date: Tue, 30 Mar 2021 23:43:26 +0800 Subject: [PATCH] Fix: fmt::ostream cannot be moved while holding buffered data #2197 (#2198) * Add a test case: move ostream while holding data * Fix moving ostream while holding data Co-authored-by: Junliang HU --- include/fmt/os.h | 2 ++ test/os-test.cc | 13 +++++++++++++ 2 files changed, 15 insertions(+) diff --git a/include/fmt/os.h b/include/fmt/os.h index 0b0b94ed..78971e37 100644 --- a/include/fmt/os.h +++ b/include/fmt/os.h @@ -396,8 +396,10 @@ class ostream final : private detail::buffer { ostream(ostream&& other) : detail::buffer(other.data(), other.size(), other.capacity()), file_(std::move(other.file_)) { + other.clear(); other.set(nullptr, 0); } + ~ostream() { flush(); delete[] data(); diff --git a/test/os-test.cc b/test/os-test.cc index 44a2988f..d9d094ce 100644 --- a/test/os-test.cc +++ b/test/os-test.cc @@ -293,6 +293,19 @@ TEST(OStreamTest, Move) { moved.print("hello"); } +TEST(OStreamTest, MoveWhileHoldingData) { + { + fmt::ostream out = fmt::output_file("test-file"); + out.print("Hello, "); + fmt::ostream moved(std::move(out)); + moved.print("world!\n"); + } + { + file in("test-file", file::RDONLY); + EXPECT_READ(in, "Hello, world!\n"); + } +} + TEST(OStreamTest, Print) { fmt::ostream out = fmt::output_file("test-file"); out.print("The answer is {}.\n", fmt::join(std::initializer_list{42}, ", "));