YiFei YiFei - 3 months ago 7
C++ Question

How can I bypass the call to destructor at end of member function?

I have a struct with a non-trivial non-copyable (anyway, copyable but very expensive) member and there's a member function that I want if I call, it would transfer the ownership of the member. See the following demo code:

class A{
// ...
};
struct s{
A instance;
A? get(){
return instance?;
}
}; // Even after s is destroyed, instance should keep on


In other words, I want to prolong the life of
instance
, then use it in other context. I tried several ways, including
return std::move(instance)
or explicit release the object to a temporary variable, but none of them worked. They will always call the destructor of instance.

So how can I achieve that, will returning const reference help?

Answer
  • An object's lifetime cannot be extended beyond its lexical scope, unless it has static or thread storage duration.
  • You cannot suppress the implicit destructor call for an object that goes out of scope, other than by calling std::exit or otherwise crashing the program.

This looks like an XY problem. Most likely, the actual solution is to have get() return A (by value) and use std::move to move the resources from s::instance to the return value, so that the destructor of s::instance is a no-op.

A get() {
    return std::move(instance);
}

But we can't say for sure if you won't tell us the actual problem.