Consider the following hierarchy:
class BaseICannotChange {};
class DerivedIControl: public BaseICannotChange {
private:
int _Value;
public:
DerivedIControl(int value): _Value{value} {}
int getValue () const {return _Value;}
};
I have a std::unique_ptr
to a DerivedIControl
. I want to retain the ability to get the value after the pointer has been moved, but while I am sure that the underlying object still exists:
int main () {
auto myDerived = std::make_unique<DerivedIControl>(42);
std::cout << "My value is: " << myDerived->getValue() << std::endl;
std::unique_ptr<BaseICannotChange> myBase = std::move(myDerived);
// This would crash as myDerived has been moved.
// std::cout << "My value is: " << myDerived->getValue() << std::endl;
return 0;
}
As I have control of DerivedIControl
, is it legit to swap the getter for a std::function
that I can then copy before moving the pointer?
class BaseICannotChange {};
class DerivedIControl: public BaseICannotChange {
private:
int _Value;
public:
DerivedIControl(int value): _Value{value} {}
std::function<int(void)> getValue = [this] () {return _Value;};
};
Now I can write this:
int main () {
auto myDerived = std::make_unique<DerivedIControl>(42);
std::cout << "My value is: " << myDerived->getValue() << std::endl;
auto myGetter = myDerived->getValue;
std::unique_ptr<BaseICannotChange> myBase = std::move(myBase);
std::cout << "My value is: " << myGetter() << std::endl;
return 0;
}
I have tried this on a couple of online compilers, and it seems to work.
Is there a catch I am not seeing that makes it undefined behavior?