c ++:尝试使用const成员构造一个类

And*_*Pro 1 c++ constructor const exception try-catch

考虑以下课程:

class MyClass
{
private:
    const unsigned int num;//num identifies the object. needs to be const
    unsigned int checkNum(unsigned int);// verifies that num has a valid value

public:
    MyClass(unsigned int n): num(checkNum(n)) {}
};

unsigned int MyClass:checkNum(unsigned int n)
{
    if (some_condition)
        throw std::invalid_argument("Invalid number");
    return n;
}
Run Code Online (Sandbox Code Playgroud)

难点在于,try由于范围检查,必须在块内构造对象:

int main()
{
    try {
        MyClass mc(1000);
    }
    catch (std::invalid_argument &ia)
    {
        std::cout << ia.what();
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

问题是mctry块之外是不可用的.

可能的解决方案:

  1. try在使用的整个范围内扩展块mc.在许多情况下不实用.

  2. 不要在构造函数中抛出异常,但之后抛出它会为时已晚.

我能想到的唯一可接受的解决方案是使用智能指针将声明带到try块之外:

int main()
{
    std::unique_ptr<MyClass> my_class_ptr;
    try {
        my_class_ptr = std::make_unique<MyClass>(1000);
    }
    catch (std::invalid_argument &ia)
    {
        std::cout << ia.what();
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

还有其他/更好的解决方案吗?

Lig*_*ica 8

mc当它的构造被视为无效时,你打算做什么,并通过例外"取消"?

具有try物体周围的整个范围扩大是非常合情合理的.

mc 应该在try街区外进出.