Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

c++ - How to handle incorrect values in a constructor?

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

Suppose I have a class like this:

class Time
{
protected:
    unsigned int m_hour;
    unsigned int m_minute;
    unsigned int m_second;
public:
    Time(unsigned int hour, unsigned int minute, unsigned int second);
};

While I would want a to be constructed successfully, I would want the constructor of b to fail.

Time a = Time(12,34,56);
Time b = Time(12,34,65); // second is larger than 60

However, this is not possible, because constructors do not return any values and will always succeed.

How would the constructor tell the program that it is not happy? I have thought of a few methods:

  1. have the constructor throw an exception, and have handlers in the calling function to handle it.
  2. have a flag in the class and set it to true only if the values are acceptable by the constructor, and have the program check the flag immediately after construction.
  3. have a separate (probably static) function to call to check the input parameters immediately before calling the constructor.
  4. redesign the class so that it can be constructed from any input parameters.

Which of these methods is most common in industry? Or is there anything I may have missed?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The typical solution is to throw an exception.

The logic behind that is the following: the constructor is a method that transforms a chunk of memory into a valid object. Either it succeeds (finishes normally) and you have a valid object or you need some non-ignorable indicator of a problem. Exceptions are the only way to make the problem non-ignorable in C++.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...