I thought to transform this working code:
ofstream outfile("my_file.txt");
copy(v.begin(), v.end(), ostream_iterator<int>(outfile));
into this:
copy(v.begin(), v.end(), ostream_iterator<int>(ofstream("my_file.txt")));
In other words, I use an "anonymous", or unnamed, version of the ofstream object.
Two questions:
(1) Why does the second attempt fail?
(2) Is the second attempt even good stylistically, or is it better in C++ to keep everything explicitly named? I'm coming from a Python background, where objects are created on the fly all the time.
Thanks!!
The ostream_iterator<T>
constructor takes a non-const
reference to a stream object, while temporaries can be passed at most as const
references (at least in C++03); the rationale for this is well explained in this question.
By the way, here there wasn't much choice about how to pass the stream: a const
reference wouldn't have made sense (the ostream_iterator
has to modify the stream), and a plain ostream
isn't acceptable because it is non-copyable (slicing would kill polymorphism).
In Python you can get away with constructing/passing stuff on the fly because you are always dealing with references to reference-counted (and garbage-collected) objects.
The C++ object semantic is radically different - an object is an object, not a reference; to obtain a semantic similar to Python's you would have to allocate every object dynamically with new
and pass them around wrapped in shared_ptr<T>
.
is it better in C++ to keep everything explicitly named
Not necessarily - it's perfectly normal to create temporaries, but you must be aware of what you can and cannot do with them, how references affect their lifetime, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With