简体   繁体   English

如何处理Boost iostreams设备的打开和关闭?

[英]How do I handle opening and closing a boost iostreams Device?

I have defined a boost Device called ZipFileDevice, that takes in an archive path, and a path to a file within that archive. 我定义了一个名为ZipFileDevice的增强设备,它使用一个存档路径以及该存档中文件的路径。

The Device defines read, write, seek, a costructor that takes the two paths, and a destructor. 设备定义读取,写入,查找,采用两条路径的构造函数和析构函数。

I am opening the zip file in the constructor of ZipFileDevice, and closing it in the destructor. 我正在ZipFileDevice的构造函数中打开zip文件,并在析构函数中将其关闭。

This is how I am using the Device: 这是我使用设备的方式:

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

My problem is that the ZipFileDevice is copied twice when creating the stream_buffer, and the copies are destroyed, closing the zip file. 我的问题是在创建stream_buffer时,ZipFileDevice被复制了两次,副本被销毁,关闭了zip文件。 When I read from the stream, the file has been closed. 当我从流中读取时,文件已关闭。

How do I correctly handle opening and closing a Device? 如何正确处理打开和关闭设备?

From the design rationale page : 设计原理页面

Filters and Devices must either be CopyConstructible or be passed to streams and stream buffers using boost::ref . 过滤器和设备必须是CopyConstructible 或者必须使用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. 模板basic_file是一个很好的例子。 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. Boost.Iostreams的预发行版本允许将动态分配的过滤器和设备作为指针传递给流和流缓冲区,这些指针将由用户选择,由Iostreams库拥有。 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. 拒绝该设计有两个原因:它不是异常安全的,并且它需要一个额外的函数参数来指示对象是否归库所有。

So, either pass boost::ref to your device, or implement a Handle/Body idiom eg with a shared_ptr<DeviceImpl> inside your Device type 因此,可以将boost::ref传递给您的设备,或者实现一个Handle / Body习惯用法,例如在您的Device类型内部使用shared_ptr<DeviceImpl>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM