Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: fmt::ostream cannot be moved while holding buffered data #2197 #2198

Merged
merged 2 commits into from
Mar 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
Comment on lines +399 to 400
Copy link
Contributor

@vitaut vitaut Mar 29, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if this can be replaced with

other = detail::buffer<char>();

Copy link
Contributor Author

@vtta vtta Mar 29, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems reasonable, but I prefer the consistency between set and clear.
Another issue is that creating an additional object in the ctor seems confusing.

}

~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