I have a object whose copy operation would be too slow so I decided to delete
it and force users to only move. A copy of this object wound't make much sense anyway. But then I have this function:
Object loadFromFile(const std::string& name) {
Object obj;
...
return obj;
}
Even though copy elision happens here and no copy constructor is called, this fails to compile because a copy constructor is required to exist and be accessible. This is my second attempt:
Object&& loadFromFile(const std::string& name) {
Object obj;
...
return std::move(obj);
}
This compiles. Yay!
But a new problem surges when trying to use it:
Object x = loadFromFile("test.txt");
This again requires a copy constructor. I couldn't get it to work even explicitly using move:
Object x = std::move(loadFromFile("test.txt"));
The only solution I came was:
const Object& x = loadFromFile("test.txt");
But x
has to be non-const as it is going to be altered later.
How to deal with it?