从std :: exception继承,std :: exception的定义不明确 [英] Inheriting from std::exception, ambiguity in definitions of std::exception

查看:159
本文介绍了从std :: exception继承,std :: exception的定义不明确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有些困惑,我一直在寻找可以为我自己的类型确定从std :: exception继承的适当方法的方法。现在根据cplusplus.com(我知道这不一定是标准,这就是我要问的原因),std :: exception是没有成员的基类。但是,在查看了我对标准库的实现(VS 2005)之后,很清楚地用两个成员变量定义了类std :: exception:

So I am a little confused, I have been looking around trying to determine an appropriate way of inheriting from std::exception for my own type. Now according to cplusplus.com (and i know this isn't necessarily the standard, thats why I'm asking), std::exception is a base class with no members. However, after looking at my implementation of the standard library (VS 2005), the class std::exception is quite clearly defined with two member variables:

class _CRTIMP_PURE exception
    {   // base of all library exceptions
        ... 
private:
    const char *_m_what;
    int _m_doFree;
    };

现在是将这些成员包括在基类std :: except中的标准,我的理解是事实并非如此。我问的原因是我的派生异常类实际上只需要一个字符串即可获取其信息,因此此实现可以正常工作。但是,我担心这是非标准的,因此我最好从std :: exception继承并自己添加适当的成员+复制/分配代码。

Now is this standard to have these members included within the base class std::exception, my understanding was that it isn't. My reason for asking is that my derived exception class really only needs a single string for its information, thus this implementation would work fine. However, I'm worried that this is non-standard, and as such I might be better off inheriting from std::exception and adding the appropriate members + copy/assignment code myself.

推荐答案

std :: exception 类的定义为:

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

关于可替代性,您必须遵守的合同。该标准定义了每个成员的细节。通常唯一需要考虑的是 what()返回一个 NULL终止的多字节字符串,适合显示为 wstring 。另一部分是服从并确保 throw()合同。

That is the contract that you have to live up to when it comes to substitutability. The Standard defines the specifics of each member. The only one that usually requires consideration is that what() returns a "null-terminated multi-byte string, suitable for display as a wstring". The other part is obeying and ensuring the throw() contract.

这篇关于从std :: exception继承,std :: exception的定义不明确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆