c++constructorfunction-try-block

How to access the object field in a constructor function-try-block?


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?


Solution

  • 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.

    Before any catch clauses of a function-try-block on a constructor are entered, all fully-constructed members and bases have already been destroyed.

    The behavior is undefined if the catch-clause of a function-try-block used on a constructor or a destructor accesses a base or a non-static member of the object.

    Every catch-clause in the function-try-block for a constructor must terminate by throwing an exception. If the control reaches the end of such handler, the current exception is automatically rethrown as if by throw;. The return statement is not allowed in any catch clause of a constructor's function-try-block.

    From cppreference