如何解决从临时
我正在使用具有(仅)构造函数的第三方类,如下所示:
class foo // cannot be altered
{
public:
explicit foo(std::istream&);
...
};
及其文档建议采取以下方法
std::ifstream from("file.txt");
foo obj(from);
from.close();
我无法更改foo
并想用作其他课程的成员
class bar
{
foo obj; // must not be altered
public:
explicit
bar(std::string const&filename) // must not be altered
: obj(std::ifstream(filename)) // error: no matching constructor
{}
...
};
除外,因为它不起作用,因为不能保证从std::ifstream
创建的临时filename
的生存时间足以构建foo obj
,因此不能转换为{{ 1}}(如果std::istream&
接受了foo::foo()
,情况将有所不同)。
所以我的问题是:我可以使const std::istream&
的构造函数在不更改bar
的设计的情况下工作吗(例如,bar
采用bar::bar()
或bar保留std::istream&
而不是std::unique_ptr<foo>
还是通过向foo
添加数据成员)?
解决方法
您的设计约束无法满足。最安全的放松方法是按住std::ifstream
中的bar
。
class bar
{
std::ifstream objs_stream; // must be declared before obj
foo obj; // must not be altered
public:
explicit
bar(std::string const&filename) // must not be altered
: objs_stream(filename),obj(objs_stream)
{}
...
};
另一种选择是向第三方课程提交补丁:
class foo
{
public:
explicit foo(std::istream&);
explicit foo(std::istream&& is) : foo(is) {}
...
};
如果foo
具有复制或移动构造函数,则可以
foo make_foo(const std::string& filename)
{
std::ifstream is(filename);
return foo(is);
}
class bar
{
foo obj; // must not be altered
public:
explicit
bar(std::string const&filename) // must not be altered
: obj(make_foo(filename))
{}
...
};
,
我想出了以下可能性(编译时没有错误)。
class bar
{
foo obj; // must not be altered
struct tmp {
mutable std::ifstream s;
tmp(std::string const&f) : s(f) {}
operator std::istream&() const { return s; }
};
public:
explicit
bar(std::string const&filename) // must not be altered
: obj(tmp(filename))
{}
...
};
可以吗?即会一直生存到tmp::s
到obj
的构造返回为止(根据foo
的文档,请参见已编辑的问题,就足够了吗?)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。