语境
尝试在内部创建一些具有不同文件名的 gzip 存档,我编写了以下代码片段。
#include <iostream>
#include <utility>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filter/gzip.hpp>
boost::iostreams::filtering_ostream&& makeGZipStream(const std::string& archiveName,
const std::string& fileName)
{
boost::iostreams::filtering_ostream theGzipStream;
boost::iostreams::gzip_params theGzipParams;
theGzipParams.file_name = fileName;
theGzipStream.push(boost::iostreams::gzip_compressor{theGzipParams});
theGzipStream.push(boost::iostreams::file_sink{archiveName});
return std::move(theGzipStream);
}
int main()
{
boost::iostreams::filtering_ostream&& theGzipStream = makeGZipStream("archive.gz", "file");
theGzipStream << "This is a test..." << std::endl;
return 0;
}
问题
这(如我们所料)会产生核心转储,因为makeGZipStream
我们尝试通过(右值)引用返回本地堆栈分配的变量。但是在这种情况下,副本不是一个选项,因为boost::iostreams::filtering_ostream
它是不可复制的。
问题
- 由于它的移动构造函数,我们可以返回一个
std::unique_ptr
“按值”(由于复制省略,移动甚至不应该在 C++17 中发生),为什么在这种情况下不可能呢? - 那里有什么好的解决方案?
可能的解决方案
- 将所有内容放在同一范围内(我试图避免的)
- 将您的对象包装在一个
unique_ptr
(不太漂亮)中 - 还要别的吗 ?
笔记
使用的编译器是相当旧的g++ (GCC) 4.9.3
.