Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

c++ - Why copying stringstream is not allowed?

int main()
{
   std::stringstream s1("This is my string.");
   std::stringstream s2 = s1; // error, copying not allowed
}

I couldn't find a reason as to why i can't copy stringstream. could you provide some reference?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Copying of ANY stream in C++ is disabled by having made the copy constructor private.

Any means ANY, whether it is stringstream, istream, ostream,iostream or whatever.

Copying of stream is disabled because it doesn't make sense. Its very very very important to understand what stream means, to actually understand why copying stream does not make sense. stream is not a container that you can make copy of. It doesn't contain data.

If a list/vector/map or any container is a bucket, then stream is a hose through which data flows. Think of stream as some pipe through which you get data; a pipe - at one side is the source (sender), on the other side is the sink (receiver). That is called unidirectional stream. There're also bidirectional streams through which data flows in both direction. So what does it make sense making a copy of such a thing? It doesn't contain any data at all. It is through which you get data.

Now suppose for a while if making a copy of stream is allowed, and you created a copy of std::cin which is in fact input stream. Say the copied object is copy_cin. Now ask yourself : does it make sense to read data from copy_cin stream when the very same data has already been read from std::cin. No, it doesn't make sense, because the user entered the data only once, the keyboard (or the input device) generated the electric signals only once and they flowed through all other hardwares and low-level APIs only once. How can your program read it twice or more?

Hence, creating copy is not allowed, but creating reference is allowed:

std::istream  copy_cin = std::cin; //error
std::istream & ref_cin = std::cin; //ok

Also note that you can create another instance of stream and can make it use the same underlying buffer which the old stream is currently using. See this : https://ideone.com/rijov


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...