如何处理打开和关闭 boost iostreams 设备?
How do I handle opening and closing a boost iostreams Device?
我已经定义了一个名为 ZipFileDevice 的增强设备,它接受一个存档路径,以及一个指向该存档中文件的路径。
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 文件。当我从流中读取时,文件已关闭。
如何正确处理打开和关闭设备?
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
传递给您的设备,要么实施 Handle/Body 习语,例如在你的 Device
中输入 shared_ptr<DeviceImpl>
类型
我已经定义了一个名为 ZipFileDevice 的增强设备,它接受一个存档路径,以及一个指向该存档中文件的路径。
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 文件。当我从流中读取时,文件已关闭。
如何正确处理打开和关闭设备?
Filters and Devices must either be
CopyConstructible
or be passed to streams and stream buffers usingboost::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
传递给您的设备,要么实施 Handle/Body 习语,例如在你的 Device
中输入 shared_ptr<DeviceImpl>
类型