I made a method that returns an object in that way:
MyObject &&
MyController::getMyObject (const otherObject & options) const
{
MyObject tmp;
tmp.doSometing(options);
return std::move(tmp);
}
Later in my code, I wanted to use that method with chained calls like this :
controller.getMyObject(options).doAnotherThing();
And it doesn't work, the call to "doAnotherThing" relies on an empty object. I know how to fix the situation :
auto tmp = controller.getMyObject(options);
tmp.doAnOtherThing();
My questions are : In the first place, is the method written correctly ? How can I avoid to write the second way for the usage ? It's really ulgy...
Note: "MyObject" is movable.
In the first place, is the method written correctly ?
No. The function returns a dangling reference.
Both the first and the second usages have undefined behaviour.
A correct way, and probably what you inteded is to return an object, rather than a reference:
MyObject
MyController::getMyObject (const otherObject & options) const
{
MyObject tmp;
tmp.doSometing(options);
return tmp;
}