gpt4 book ai didi

c++ - 如何避免将 std::string 放入异常类中?

转载 作者:可可西里 更新时间:2023-11-01 17:46:56 25 4
gpt4 key购买 nike

这是我的异常类:

class Win32Failure : public std::exception
{
public:
Win32Failure( char const* win32_function_name, LONG error_code );

char const* win32_function_name() const { return win32_function_name_; }
LONG error_code() const { return error_code_; }

virtual char const* what() const;

private:

std::string GetFormattedMessage() const;

char const* win32_function_name_;
LONG error_code_;
std::string error_text_;
};

Win32Failure::Win32Failure( char const* win32_function_name, LONG error_code )
: error_code_(error_code)
, win32_function_name_(win32_function_name)
{
std::stringstream error_msg;
error_msg << win32_function_name << " failed with code: "
<< error_code << " (" << GetFormattedMessage() << ")"
;

error_text_ = error_msg.str();
}

std::string Win32Failure::GetFormattedMessage() const
{
TCHAR message_buffer[1000];

FormatMessage(
//FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
error_code_,
0, // Default language
reinterpret_cast<LPTSTR>(&message_buffer),
sizeof(message_buffer) / sizeof(TCHAR),
NULL
);

return std::string(message_buffer);
}

char const* Win32Failure::what() const
{
return error_text_.c_str();
}

boost exception guidelines建议不要放置任何分配内存的对象作为我的异常类的成员。在这种情况下,std::string 的使用违反了这一点。我尊重这个规则,但是我想不出一种方法来实现 what() 覆盖而不使用 std::string 来管理内存(而不是要求调用者为我管理它).

我可以使用固定大小的缓冲区作为成员并使用 C 库函数(如 snprintf())来完成这项工作,但这不是 C++ 的惯用方式,因此不是理想的解决方案。

这是异常类的合适实现吗?如果不是,可以进行哪些改进?

最佳答案

就其值(value)而言,<stdexcept> 中定义的所有异常类型拿std::string作为参数。这可以被库设计者解释为“没问题”。我认为反对这一点的主要论据是,如果您处于内存受限的环境中,您可能无法分配内存来抛出异常。

关于c++ - 如何避免将 std::string 放入异常类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9403885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com