C++ 构造函数中的自定义异常抛出 ()
C++ Custom exception throw () in constructor
所以我读到在自定义异常类中除了基本类型之外不应该有任何其他类型,否则它可能会在异常中抛出异常(就像梦中的梦(。并且您应该按值抛出并按引用捕获。
我有这个作为我的异常类头:
class DeepthroatException : public std::runtime_error {
public:
DeepthroatException(const char* err); // set err member to err
private:
// Error description
const char* err;
};
但我不喜欢它,因为它引入了内存管理问题,这是肉眼看不见的,我需要使用地雷探测器。如果可能的话,我想改成std::string
。
但是上面第一段有问题,所以我想这样做:
#include <string>
class DeepthroatException : public std::runtime_error {
public:
DeepthroatException(std::string err) throw(); // set err member to err, no throw
private:
// Error description
std::string err;
};
可以这样做吗?
使用std::string
也会让你在std::bad_alloc
上度过一段糟糕的时光。但是这个问题已经是std::runtime_error
固有的,因为它的构造函数可以把std::string
当作参数:
explicit runtime_error( const std::string& what_arg );
explicit runtime_error( const char* what_arg );
之所以如此,是因为复制异常永远不会引发,因此实现可能会分配另一个字符串并将参数的内容复制到其中。如果您确实不希望抛出第二个异常,请将构造函数标记为 noexcept
并确保它永远不会失败,如果失败,您的程序将立即关闭。
您可以通过使用构造函数中的字符串构造std::runtime_error
行为来继承它,如下所示:
DeepthroatException(const std::string& err) noexcept :
std::runtime_error(err)
{
// ...
}
此时,您可以删除err
数据成员,因为runtime_error
将为您提供内部字符串,您可以通过what()
引用该字符串。
相关文章:
- C++ 中的自定义异常:在哪里定义它们?
- 添加自定义析构函数时,Move 构造函数在派生类中消失
- 我应该C++自定义异常代码放在哪里?
- 为什么为派生类定义复制构造函数需要定义基类的默认构造函数?
- 使用迭代器的自定义比较器函数
- 为什么定义复制构造函数会给我错误:无法将类型 'obj&' 的非常量左值引用绑定到类型为"obj"的右值?
- 为什么在类或结构中传递自定义比较器函数?
- C++中用户定义的构造函数出现问题
- 自定义异常中的用户定义的空构造函数,具有多个继承和抽象基类
- C++ 乘法定义的构造函数错误消息似乎错误
- openCV Mat 中的值在自定义类构造函数中设置后不会保留
- 初始化自定义类型构造函数的数组
- 自定义对象构造函数在循环外部循环
- C++ 构造函数中的自定义异常抛出 ()
- 如何在C++中使用默认和自定义复制构造函数
- 尝试在没有new的情况下使用我的自定义类构造函数
- 带有自定义散列函数(bstrt)的无序映射仅适用于默认构造函数(重复键)
- 如何在c++中编写自定义异常类时重载throw函数
- 关于C++中的分段错误的问题很可能是由自定义复制构造函数引起的
- C++从函数返回对象时使用自定义复制构造函数