开发者

Beginner question about getting reference to cin

I'm having problems wrapping my head around this. I have a 开发者_运维问答function

void foo(istream& input) {
     input = cin;
}

This fails (I'm assuming because cin isn't supposed to be "copyable".

however, this works

void foo(istream& input) {
    istream& baz = cin;
}

Is there a reason that I can get a reference to cin in baz but I cannot assign it to input?

Thanks


This syntax:

void foo(istream& input) {
     input = cin;
}

Doesn't create a reference. it invokes the operator= which is meant to copy things around.
This syntax however:

void foo(istream& input) {
    istream& baz = cin;
}

defines a new reference variable.

The key point is that in C++ you can't change a reference once you've declared it.
After the declaration the reference behaves as if it is the object referenced to itself. So using operator= on it tries to copy into it.


This is perfectly reasonable.

Cloning something and creating alias to it are different operations.


& (reference) actually works as a name alias, so all your changes are actually done on the object you're referring.

Hence, the first chunk of code fails, because you're working directly with your aliased stream which has a inaccessible (private) operator= in it.

Your second chunk of code actually means you're creating another name alias, therefore it's valid.


A reference must be initialized, but cannot be assigned to. Unfortunately, initialization and assignment (can) both use =, so it's not always obvious which is which. In this case that difference is crucial though.

When you do istream& baz = cin;, you're initializing the reference, but doing nothing to the istream itself. When you do input = cin;, it's not initialization, because at that point input has already been initialized. That leaves only one other possibility: assignment. Since you can't assign to the reference itself, however, it's interpreted as attempting to assign cin to the stream referenced by input. Since streams can't be assigned, the compiler rejects that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜