I came across come C++ code similar to the following (more or less minimal) example. Please consider the marked method call in the function on the bottom:
#include <memory>
static unsigned returnValue = 5;
void setReturnValue(unsigned u) { returnValue = u; }
class MyObject
{
public:
MyObject(unsigned uIN) : u(uIN) {}
~MyObject() { u = 42; }
void method(std::unique_ptr<MyObject> uniqPtrToObject)
{
// Do something fancy with this unique pointer now,
// which will consume the object and its data
setReturnValue(uniqPtrToObject->getValue());
}
unsigned getValue() { return u; }
private:
unsigned u; // Some relevant object data
};
std::unique_ptr<MyObject> GetUniqToObject(unsigned u)
{
// Get the object in a fancy way. For now, assume it has just been constructed.
return std::make_unique<MyObject>(u);
}
int main()
{
std::unique_ptr<MyObject> uniqPtrToObject = GetUniqToObject(0);
// ===================================================
// Oops!
uniqPtrToObject->method(std::move(uniqPtrToObject));
// ===================================================
return returnValue;
}
It looks really strange to move away an object while calling one of its methods.
I already tried my example on https://godbolt.org (x64-86 gcc 12.2
), and the program returned 0
as it "should". Just some fortunate coincidence?
I still wonder:
- Is this valid C++ syntax?
- If so, is it portable?
- If so, is it moral?
As I haven't found a good resource where to start research on this situation, I hope you have some advice where to start reading or how to decide this situation easily.