Is it reasonable to take std::istream&& as a argument?

Viewed 687

I have encountered code which does this:

SomeObject parse (std::istream && input) {....

The input argument is an rvalue reference, which normally means the function is intended to take ownership of the argument. That's not quite what is happening here.

The parse function will completely consume the input stream, and it demands an rvalue reference because then calling code will give away ownership of the istream and hence this is a signal that the input stream will be unusable.

I think this is okay because, since the parse function doesn't actually move the object around, there is no danger of slicing out the subtype. This is basically behaving as a normal reference from parse's point of view, only there is a kind of compilable comment to the calling function that you have to give up ownership of the stream.

Is this code actually safe? Or is there some overlooked subtlety which makes this dangerous?

4 Answers

An std::istream isn't moveable, so there's no practical benefit to this.

This already signals that the thing may be "modified", without the confusion of suggesting you're transferring ownership of the std::istream object (which you're not doing, and can't do).

I can kind of see the rationale behind using this to say that the stream is being logically moved, but I think you have to make a distinction between "ownership of this thing is being transferred", and "I keep ownership of this thing but I will let you consume all of its services". Ownership transfer is quite well understood as a convention in C++, and this is not really it. What will a user of your code think when they have to write parse(std::move(std::cin))?

Your way isn't "dangerous" though; you won't be able to do anything with that rvalue reference that you can't with an lvalue reference.

It would be far more self-documenting and conventional to just take an lvalue reference.

std::move just produces an rvalue reference from an object and nothing more. The nature of an rvalue is such that you can assume nobody else will care about it's state after you're done with it. std::move then is used to allow developpers to make that promise about objects with other value categories. In other words calling std::move in a meaningful context is equivalent to saying "I promise I don't care about this object's state anymore".

Since you will be making the object essentially unusable and you want to make sure the caller won't use the object anymore using an rvalue reference enforces this expectation to some extent. It forces the caller to make that promise to your function. Failure to make the promise will result in a compiler error (assuming there isn't another valid overload). It does not matter if you actually move from the object or not, only that the original owner has agreed to forfeit it's ownership.

What you're trying to do here is not "dangerous" in the sense that, given the current std::istream interface, there don't seem to be any circumstances under wich taking an rvalue reference here would necessarily lead to undefined behavior when taking an lvalue reference wouldn't have. But the semantics of this whole contraption are IMHO very questionable at best. What does it mean for the calling code to "give away ownership" but at the same time "not transferring it"? Who "owns" the stream after parse() returns!? In what way exactly does parse() make the stream "unusable"? What if parsing fails due to some error before the entire stream is "consumed"? Is the stream "unusable" then!? Is no one allowed to try read the rest? Is "ownership" somehow "given back" to the calling code in this case?

A stream is an abstract concept. The purpose of the stream abstraction is to serve as an interface through which someone can consume input without having to know where the data comes from, lives, or how it is accessed and managed. If the purpose of parse() is to parse input from arbitrary sources, then it should not be concerned with the nature of the source. If it is concerned with the nature of the source, then it should request a specific kind of source. And this is where, IMHO, your interface contradicts itself. Currently, parse() takes an arbitrary source. The interface says: I take whatever stream you give me, I don't care how it's implemented. As long as it's a stream, I can work with it. At the same time, it requires the caller to relinquish the object that actually implements the stream. The interface requires the caller to hand over something that the interface itself prevents any implementation behind the interface to ever know about, access, or use in any way. For example, how would I have parse() read from an std::ifstream? Who closes the file afterwards? If can't be the parser. It also can't be me because calling the parser forced me to hand over the object. At the same time, I know that the parser could never even know it had to close the file I handed over…

It'll still do the right thing in the end because there was no way an implementation of the interface could've actually done what the interface suggested it would do and so my std::ifstream destructor will just run and close the file. But what exactly did we gain by lying to each other like that!? You promised to take over the object when you were never going to, I promised to never touch the object again when I knew I'll always have to…

Your assumption that rvalue reference parameter imply "taking ownership" is completely incorrect. Rvalue reference is just a specific kind of reference, which comes with its own initialization rules and overload resolution rules. No more, no less. Formally, it has no special affinity with "moving" or "taking ownership" of the referenced object.

It is true that support for move semantics is considered one of the primary purposes of rvalue references, but still you should not assume that this is their only purpose and that these features are somehow inseparable. Just like any other language feature, it might allow a significant number of well-developed alternative idiomatic uses.

An example quote similar to what you just quoted is actually present in the standard library itself. It is the extra overloads introduced in C++11 (and C++17, depending on some nuances)

template< class CharT, class Traits, class T >
basic_ostream< CharT, Traits >& operator<<( basic_ostream<CharT,Traits>&& os, 
                                            const T& value );

template< class CharT, class Traits, class T >
basic_istream<CharT,Traits>& operator>>( basic_istream<CharT,Traits>&& st, T&& value );

Their main purpose is to "bridge" the difference in the behavior between member and non-member overloads of operator <<

#include <string>
#include <sstream>

int main() 
{
  std::string s;
  int a;

  std::istringstream("123 456") >> a >> s;
  std::istringstream("123 456") >> s >> a;
  // Despite the obvious similarity, the first line is well-formed in C++03
  // while the second isn't. Both lines are well-formed in C++11
}

It takes advantage of the fact that rvalue reference can bind to temporary objects and still see them as modifiable objects. In this case rvalue reference is used for purposes that have nothing to do with move semantics. This is perfectly normal.

Related