gpt4 book ai didi

c++ - 如何处理打开和关闭 boost iostreams 设备?

转载 作者:太空宇宙 更新时间:2023-11-04 13:31:23 25 4
gpt4 key购买 nike

我已经定义了一个名为 ZipFileDevice 的 boost 设备,它接受一个存档路径,以及一个指向该存档中文件的路径。

Device 定义了读取、写入、查找、采用这两条路径的构造函数和析构函数。

我在 ZipFileDevice 的构造函数中打开 zip 文件,并在析构函数中关闭它。

这就是我使用设备的方式:

boost::iostreams::stream_buffer<ZipFileDevice> kBuff("path/to/archive", "path/to/file");
std::iostream kStream(&kBuff);
kStream.read(...);

我的问题是在创建 stream_buffer 时 ZipFileDevice 被复制了两次,拷贝被销毁,关闭了 zip 文件。当我从流中读取时,文件已关闭。

如何正确处理打开和关闭设备?

最佳答案

来自design rationale page :

Filters and Devices must either be CopyConstructible or be passed to streams and stream buffers using boost::ref.

This requirement can complicate the design of Filters and Devices, since some components that could otherwise be non-copyable must use reference counting.

The template basic_file is a good illustration. A pre-release version of Boost.Iostreams allowed dynamically allocated Filters and Devices to be passed to streams and stream buffers as pointers that would become owned by the Iostreams library at the user's option. This design was rejected for two reasons: it was not exception safe, and it required an extra function parameter to indicate whether an object was to become owned by the library.

所以,要么通过 boost::ref到您的设备,或实现一个句柄/主体习语,例如用shared_ptr<DeviceImpl>在你的里面 Device类型

关于c++ - 如何处理打开和关闭 boost iostreams 设备?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31332790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com