In C ++, we also often build objects on the fly, but we need to consider ownership issues.
The problem with ostream_iterator<int>(ofstream("my_file.txt")) is that the temporary object is passed to the constructor, but the constructed ostream_iterator object does not take responsibility for temporary responsibilities. If ostream_iterator also not temporary, it continued to hold the invalid link in the next line of code.
There are ways to get around this by going to the identification function or by casting. But they tend to sacrifice security, in the sense that if you use such a mechanism for a constant variable, it will create a dangling link.
If you have multiple objects linked by links without binding to a container, the current best practice of C ++ is to use named objects, not temporary ones.
If you don't like this, you can use generic pointers more often. This template allows you to share property between multiple links, while the container is hidden. But this is not part of iostreams, and as a constructive solution here would be a little doubtful.
source share