How to handle incorrect values in a constructor?

后端 未结 11 1375
野性不改
野性不改 2020-12-17 08:44

Please note that this is asking a question about constructors, not about classes which handle time.

Suppose I have a class like this:



        
11条回答
  •  别那么骄傲
    2020-12-17 09:39

    Normally I'd say (1). But if you find that callers are all surrounding the construction with try/catch, then you can provide the static helper function in (3) as well, since with a bit of preparation the exception can be made impossible.

    There is another option, although it has significant consequences for coding style so should not be adopted lightly,

    5) Don't pass the parameters into the constructor:

    class Time
    {
    protected:
        unsigned int m_hour;
        unsigned int m_minute;
        unsigned int m_second;
    public:
        Time() : m_hour(0), m_minute(0), m_second(0) {}
        // either return success/failure, or return void but throw on error,
        // depending on why the exception in constructor was undesirable.
        bool Set(unsigned int hour, unsigned int minute, unsigned int second);
    };
    

    It's called two-phase construction, and is used precisely in situations where it is undesirable or impossible for constructors to throw exceptions. Code using nothrow new, to be compiled with -fno-exceptions, is probably the classic case. Once you get used to it, it is slightly less annoying than you might at first think.

提交回复
热议问题