From 0f3a15b3b921023e36fc9d747e685dd16119d37a Mon Sep 17 00:00:00 2001 From: silver-ymz Date: Sat, 23 Sep 2023 12:15:49 +0800 Subject: [PATCH] feat(bindings/cpp): make ReaderStream manage the lifetime of Reader Signed-off-by: silver-ymz --- bindings/cpp/include/opendal.hpp | 15 +++++++++------ bindings/cpp/tests/basic_test.cpp | 2 +- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/bindings/cpp/include/opendal.hpp b/bindings/cpp/include/opendal.hpp index 1440e84b604..10b73cf27b8 100644 --- a/bindings/cpp/include/opendal.hpp +++ b/bindings/cpp/include/opendal.hpp @@ -197,8 +197,7 @@ class Operator { * @details It provides basic read and seek operations. If you want to use it * like a stream, you can use `ReaderStream` instead. * @code{.cpp} - * auto reader = operator.reader("path"); - * opendal::ReaderStream stream(reader); + * opendal::ReaderStream stream(operator.reader("path")); * @endcode */ class Reader @@ -221,15 +220,19 @@ class Reader /** * @class ReaderStream * @brief ReaderStream is a stream wrapper of Reader which can provide - * `iostream` interface. - * @note It's an undefined behavior to make multiple streams from one reader. + * `iostream` interface. It will keep a Reader inside so that you can ignore the + * lifetime of original Reader. */ class ReaderStream : public boost::iostreams::stream> { public: - ReaderStream(Reader &reader) + ReaderStream(Reader &&reader) : boost::iostreams::stream>( - boost::ref(reader)) {} + boost::ref(reader_)), + reader_(std::move(reader)) {} + +private: + Reader reader_; }; /** diff --git a/bindings/cpp/tests/basic_test.cpp b/bindings/cpp/tests/basic_test.cpp index 096164ec367..445e6258402 100644 --- a/bindings/cpp/tests/basic_test.cpp +++ b/bindings/cpp/tests/basic_test.cpp @@ -117,7 +117,7 @@ TEST_F(OpendalTest, ReaderTest) { reader.seek(0, std::ios::beg); // stream - opendal::ReaderStream stream(reader); + opendal::ReaderStream stream(std::move(reader)); auto read_fn = [&](std::size_t to_read, std::streampos expected_tellg) { std::vector v(to_read);