在包装C库的C++类中抛出什么?

ere*_*eOn 3 c c++ memory-management exception wrapper

我必须C++围绕现有的C库创建一组包装类.

对于C库的许多对象,构造是通过调用类似britney_spears* create_britney_spears()和相反的函数来完成的void free_britney_spears(britney_spears* brit).

如果分配britney_spears失败,则create_britney_spears()返回NULL.

据我所知,这是一种非常常见的模式.

现在我想把它包装在一个C++类中.

//britney_spears.hpp

class BritneySpears
{
  public:

    BritneySpears();

  private:

    boost::shared_ptr<britney_spears> m_britney_spears;
};
Run Code Online (Sandbox Code Playgroud)

以下是实施:

// britney_spears.cpp

BritneySpears::BritneySpears() :
  m_britney_spears(create_britney_spears(), free_britney_spears)
{
  if (!m_britney_spears)
  {
    // Here I should throw something to abort the construction, but what ??!
  }
}
Run Code Online (Sandbox Code Playgroud)

所以问题出在代码示例中:我应该抛弃什么来中止构造函数?

我知道我几乎可以扔任何东西,但我想知道通常做什么.我没有关于分配失败原因的其他信息.我应该创建自己的异常类吗?std这种情况有例外吗?

非常感谢.

小智 5

您不希望派生BritneyFailedToConstruct异常.我的经验是你应该保持异常层次结构尽可能平坦(每个库使用一种类型).该异常应该来自std :: exception,并且应该以某种方式包含可通过std:; exceptions virtual what()函数访问的消息.然后将其抛出到构造函数中:

throw MyError( "failed to create spears object" );
Run Code Online (Sandbox Code Playgroud)

以下是我在自己的实用程序库中使用的异常类的声明:

class Exception : public std::exception {

    public:

        Exception( const std::string & msg = "" );
        Exception( const std::string & msg, int line,
                        const std::string & file );

        ~Exception() throw();

        const char *what() const throw();
        const std::string & Msg() const;

        int Line() const;
        const std::string & File() const;

    private:

        std::string mMsg, mFile;
        int mLine;
};

#define ATHROW( msg )\
{   \
    std::ostringstream os;  \
    os << msg               \
    throw ALib::Exception( os.str(), __LINE__, __FILE__  ); \
}   \
Run Code Online (Sandbox Code Playgroud)

该宏用于方便地添加文件名和行号,并为消息提供流格式.这可以让你说:

ATHROW( "britney construction failed - bad booty value of " << booty );
Run Code Online (Sandbox Code Playgroud)

  • 你想要小心扔掉那些矛.你会有人注意的! (6认同)