Why copying a string is not allowed?

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

I could not find the reason why I can not copy the stringstream. could you provide some link?

+47
c ++ stringstream
May 15 '11 at 19:59
source share
3 answers

Copying ANY stream in C ++ is disabled by making the copy constructor private .

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

Copying a stream is disabled because it does not make sense. It is very important to understand what a stream means in order to understand why copying a stream makes no sense. stream not a container that you can make. It does not contain data.

If the list / vector / map or any container is a bucket, then the stream is the hoses through which the data flows. Think of a stream as some kind of pipe through which you receive data; pipe - on the one hand - the source (sender), on the other hand - the receiver (receiver). This is called unidirectional flow. There are also bidirectional streams through which data flows in both directions. So what does it mean to make a copy of this? It does not contain any data. It is through this that you receive the data.

Suppose for a while, if you make a copy of the stream is valid, and you created a copy of std::cin , which is actually the input stream. Say the copied copy_cin object. Now ask yourself: it makes sense to read data from the copy_cin stream when the same data has already been read from std::cin. No, this does not make sense, because the user entered the data only once, the keyboard (or input device) generated electrical signals only once, and they flowed through all other hardware and the low-level API only once. How can your program read it twice or more?

Therefore, creating a copy is not allowed, but linking 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 the stream and make it the same base buffer that the old stream uses. See this: https://ideone.com/rijov

+71
May 15 '11 at 20:10
source share

To directly answer the question, you cannot copy, because the copy constructor for the stringstream class is declared as private.

This was probably declared like this because in most cases it seems inconvenient to copy the stream, so none of the stream classes have public copy constructors.

+4
May 15 '11 at 20:03
source share

As mentioned above, you cannot copy the stream, but if you need to, you can copy the data:

 std::stringstream from; std::stringstream to; std::copy(std::istream_iterator<char>(from), std::istream_iterator<char>(), std::ostream_iterator<char>(to)); 
+1
May 16 '11 at 16:04
source share



All Articles