class MyClass {
public:
MyClass::MyClass(std::string name) try
: name(std::move(name)),
someOtherField(WillProbablyThrowSomeException()) {
} catch (std::runtime_error &e) {
std::cout << name << " " << e.what() << std::endl;
}
private:
std::string name;
SomeOtherClass someOtherField;
}
I want to access some fields of the object from the constructor function-try-block. If I do just name
it would be illegal, since it's already moved by the time the catch-block is reached. If I do this->name
it would also be illegal, since the object is in undefined state (is it?). Is there a way to access this variable somehow?
You don't have an object in the catch, it is in the defined state of fully destructed. You are required to exit the catch block with a throw (possibly implicitly). At this point the data that was in
name
has been lost.From cppreference