I have a function which looks something like this, it returns a noncopyable class by movesemantics:
MyClass&& MyFunction() {
MyClass myClass;
do some stuff;
return std::move(myClass);
}
And then it’s accessed by
main() {
MyClass myClass = MyFunction();
}
The class utilizes boost::noncopyable for copyprevention. It has constructor, move constructor and move assignment.
My problem is, the destructor gets called before the move constructor. What have I done wrong?
You are returning a reference to a local variable. It doesn’t matter if it is an lvalue reference or an rvalue reference.
You probably should just do
and let the compiler figure out how to copy or move the result.