【发布时间】:2016-06-16 05:37:29
【问题描述】:
我创建了一个从 std::istream 派生的自定义 istream,当文件是压缩文件时使用自定义 streambuf,否则使用 std::filebuf。
#mystream.h
class my_stream: public istream {
public:
explicit my_stream(const std::string &path);
private:
std::unique_ptr<std::streambuf> b_;
}
#mystream.cpp
my_stream::my_stream(const std::string &path) :std::istream(nullptr) {
if(path.substr(path.length()-6, path.length())==".gzip"){
b_ = std::make_unique<gzipbuf>(path); //gzipbuf is derived from std::streambuf
}
else {
std::unique_ptr<std::filebuf> fb;
fb->open(path.c_str(), std::ios::in);
b_ = fb;
}
this->init(b_.get());
}
我可以在一个地方将派生类 unique_ptr 分配给基类 unique_ptr
b_ = std::make_unique<gzipbuf>(path);
但不是在另一个
b_ = fb;
它说
candidate function not viable: no known conversion from 'unique_ptr<std::filebuf, default_delete<std::basic_filebuf<char>>>' to 'unique_ptr<std::basic_streambuf<char>, default_delete<std::basic_streambuf<char>>>' for 1st argument
operator=(unique_ptr&& __u) noexcept
【问题讨论】:
-
你需要移动它:
b = std::move(fb);因为这里只能是一个(没有副本)。
标签: c++ oop c++11 unique-ptr