开发者

Why does std::exception have extra constructors in VC++?

Something I noticed just now. Definition of exception in the standard (18.6.1):

class exception {
public :
    exception() throw();
    exception(const exception &) throw();
    exception& operator=(const exception&) throw();
    virtual ~exception() throw();
    virtual const char* what() const throw();
};

Definition of exception in MSDN:

class exception {
public:
   exception(); 
   exception(const char *const&);
   exception(const char *const&, int);
   exception(const exception&); 
   exception& operator=(const exception&); 
   virtual ~exception();
   virtual const char *what() const;
};

It would seem that Microso开发者_StackOverflow中文版ft's version allows you to specify the error message for an exception object, while the standard version only lets you do that for the derived classes (but doesn't prevent you from creating a generic exception with an undefined message).

I know this is pretty insignificant, but still. Is there a good reason for this?


Not really any good reason. The MS implementation has chosen to put the string handling in std::exception instead of in each class derived from it (<stdexcept>).

As they actually also provide the interface required by the standard, this can be seen as a conforming extension. Programs following the standard works as expected.

Other implementations do not do it this way, so portable programs should not use the extra constructors.


Getting rid of the throw specification was a good idea. Although they shouldn't throw, throw specifications are generally bad.

Putting in extensions will make code non-portable but is likely to fix slicing issues where people "catch" a std::exception by value and it can copy the string in locally from what it is copying in.

I don't see the advantage in the int, nor of non-explicit constructors that take one parameter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜