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

僤鯓⒐⒋嵵緔 提交于 2019-12-06 16:45:00

问题


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 Microsoft'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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5157206/why-does-stdexception-have-extra-constructors-in-vc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!