gpt4 book ai didi

c++ - 在 C++ 中抛出原始类型

转载 作者:行者123 更新时间:2023-11-28 02:06:09 26 4
gpt4 key购买 nike

我正在处理一个请求用户提供文件、用户名和密码的对话框。我希望用户在他们的选择出现问题时得到通知。在我检查对话框的名称和密码字段之前,该文件必须有效。我知道还有其他方法可以做到这一点,我的问题是关于这个过程的效率。

我的 MFC C++ 应用程序有一个字符串表,其中使用将翻译单元映射到整数 (#define IDS_SOME_ERROR 100) 的宏来识别字符串,MFC 框架可以使用这些整数从字符串表中加载一个字符串。

我很好奇抛出原始类型的效率,所以我研究了 cpprefrence.com 上的 throw 关键字。 .

The throw expression statement copy-initializes the exception object from expression (this may call the move constructor for rvalue expression, and the copy/move may be subject to copy elision), then transfers control to the exception handler with the matching type whose compound statement or member initializer list was most recently entered and not exited by this thread of execution. Even if copy initialization selects the move constructor, copy initialization from lvalue must be well-formed, and the destructor must be accessible (since C++14).

这里是 another question在询问要抛出的类型时,我注意到一条评论说不要抛出 intstring 之类的东西。这是为什么?

这是我的代码:

void SomeDialog::OnOK()
{
UpdateData();

try
{
if (VerifySomeFile(myFileStruct.getPath()))
{
if (DialogNameField.IsEmpty())
{
throw IDS_ERROR_NOID; // "No name specified."
}

if (DialogPasswordField.IsEmpty())
{
throw IDS_ERROR_NOPWD; // "No password specified."
}

CDialog::OnOK();
}
else
{
throw IDS_BAD_FILE; // "Bad or expired file."
}
}
catch (int errIDS)
{
CString tempStr;
tempStr.LoadString(errIDS);
AfxMessageBox(tempStr, MB_OK);
}
}

因为 int 是 C++ 中的原始类型,throw 语句是否仍需要执行任何复制?以这种方式在 C++ 中抛出原始类型是否安全?删除 catch block 并将我的错误对话框逻辑从 catch block 放置到每个抛出位置会更有效吗?如果我这样做,我还必须嵌套我的代码,以便在出现多个错误时只显示一个对话框。

最佳答案

您不必过分担心效率,因为捕获std::exeption 派生的推荐做法是使用const 无论如何都要引用。

它的优点是引入异常层次结构,并使用 const char* std::exception::what() const 提供覆盖的错误消息。

关于c++ - 在 C++ 中抛出原始类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37354395/

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