【发布时间】:2016-07-03 06:38:55
【问题描述】:
使用rdbuf 和copyfmt 来制作iostream 对象的本地副本是possible。这允许在本地范围内进行格式更改:
std::ostream & operator << ( std::ostream & os, foo const & smth ) {
cloned_ostream cs( os );
cs << std::hex << smth.num;
// os is not switched to hexadecimal, which would be a confusing side-effect
return os;
}
为什么流类不提供复制构造函数来做到这一点?
相关的 C++ 最佳实践被设计为不可复制后是否发生了变化?
【问题讨论】:
-
好吧,我一定在想别的事
-
您可能已经命名了该函数克隆,但我当然不会。它当然不符合 OO 克隆概念的语义。
-
@BenjaminLindley 对,iostreams 具有引用语义,此函数通常复制基本切片。这只是一个例子。
-
An istream object, for example, represents a stream of input values, some of which may have already been read, and some of which will potentially be read later. If an istream were to be copied, would that entail copying all the values that had already been read as well as all the values that would be read in the future? The easiest way to deal with such questions is to define them out of existence. Prohibiting the copying of streams does just that--Effective Modern C++(Scott Meyers) -
它们是不可复制的,因为它们的资源无法共享而不会带来巨大的开销。指出这一点:如果你销毁
os,然后使用cs,它就没有地方可以写了。
标签: c++ iostream copy-constructor