Skip to content

Commit

Permalink
Fix: fmt::ostream cannot be moved while holding buffered data #2197 (#…
Browse files Browse the repository at this point in the history
…2198)

* Add a test case: move ostream while holding data

* Fix moving ostream while holding data

Co-authored-by: Junliang HU <[email protected]>
  • Loading branch information
vtta and vtta authored Mar 30, 2021
1 parent 7d8c340 commit 1484887
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
2 changes: 2 additions & 0 deletions include/fmt/os.h
Original file line number Diff line number Diff line change
Expand Up @@ -396,8 +396,10 @@ class ostream final : private detail::buffer<char> {
ostream(ostream&& other)
: detail::buffer<char>(other.data(), other.size(), other.capacity()),
file_(std::move(other.file_)) {
other.clear();
other.set(nullptr, 0);
}

~ostream() {
flush();
delete[] data();
Expand Down
13 changes: 13 additions & 0 deletions test/os-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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<int>{42}, ", "));
Expand Down

0 comments on commit 1484887

Please sign in to comment.