Reputation: 7981
I am working on a "filesystem" for my application to handle file operations like listing, creating, removing files and directories, and get file data. I want to use std::fstream for that because its safer and easier to format than the C FILE Handler. But i cannot return a stream object from the function (it doesn't have a copy c'tor) and when I am trying to return the reference I am getting a warning (i not warning doesn't mean that much but I am trying to fix every possible warning in my app and I did all of it until now): "warning: returning a reference to temporary". What can I do? If someone encountered this situation and found a better way to handle it, please tell.
EDIT:
std::ofstream &Filesystem::createFile(const String &str) {
std::ofstream file(str);
return file;
}
this is what I am trying to achieve. But due to the warning i am looking for another way.
Thanks in advance,
Gasim Gasimzada
Upvotes: 1
Views: 3453
Reputation: 355147
In C++0x stream objects are movable so you can in fact return a stream object by value:
// Perfectly valid C++0x
std::ofstream f()
{
return std::ofstream("pwnies.txt");
}
The Visual C++ 2010 Standard Library implementation includes movable streams, as does libc++. If you need to target older compiler/library implementations that don't support rvalue references and movable streams, you can't do this, but for new code that doesn't have any such constraints, this is the way to go.
Upvotes: 4
Reputation: 33645
Use a smart pointer, something like may work (or one of the newer std::unique_ptr
, etc.)
std::auto_ptr<std::iostream> foo()
{
return std::auto_ptr<std::iostream>(new fstream(...));
}
Upvotes: 5
Reputation: 70020
You can pass the fstream
as an argument to your function by reference.
fstream obj;
void Modify (fstream &obj) // no return, just pass by reference
{
//...
}
Upvotes: -1