Voko
Voko

Reputation: 778

C++ return directly from operator<<

Is it allowed to directly return while we are sending to ostream?

For example, instead of writing:

ostream& operator<<(ostream& os, Foo foo) {
    os << foo.a << foo.b;
    return os;
}

Instead, can I directly write:

ostream& operator<<(ostream& os, Foo foo) {
    return os << foo.a << foo.b;
}

I tried it, and it seems to work but I don't know if it's the right thing to do. Is there any problem with doing the second version?

Upvotes: 3

Views: 83

Answers (2)

Adrian Mole
Adrian Mole

Reputation: 51864

The two code snippets you post are entirely equivalent.

Why? Because (I'm assuming here, for the sake of argument, that foo.a and foo.b are simple data types like int) the << operator for std::ostream returns a reference to itself (see the "Return Value" section in the linked document).

Thus, in your first code snippet, the return os; line returns a reference to the os object referenced by the first argument. In your second snippet, the two << operations each evaluate as a reference to that same object ... so you are returning a reference to the exact same object.

To make the second version a bit clearer, you may like to enclose the returned expression in parentheses:

ostream& operator<<(ostream& os, Foo foo) {
    return (os << foo.a << foo.b);
}

Upvotes: 2

eerorika
eerorika

Reputation: 238401

Is it allowed to directly return while we are sending to ostream?

Yes, it is allowed.

Upvotes: 0

Related Questions