[英]Using boost message_queue otuside try/catch block
int main(int argc, char **argv)
{
FreeConsole();
// Cannot construct mq here, it might fail
// Declaring it here like `ipc::message_queue mq;`
// throws some weird error given below
try
{
ipc::message_queue mq(ipc::open_only, g_szPipeName);
mq.send(g_szMsgReady, sizeof(g_szMsgReady) + 1, 0);
}
catch (const ipc::interprocess_exception &ex)
{
MessageBox(nullptr, TEXT("This process is not meant to be used directly, yet ;)"), nullptr, MB_OK);
exit(-1);
}
// How to use `mq` here?
return 0;
}
當我聲明message_queue
時拋出錯誤:
Error (active) E0330
"boost::interprocess::message_queue_t<VoidPointer>::message_queue_t() [with VoidPointer=boost::interprocess::offset_ptr<void, ptrdiff_t, uintptr_t, 0Ui64>]" (declared at line 71 of "C:\dev\vcpkg\installed\\x64-windows\include\boost/interprocess/ipc/message_queue.hpp") is inaccessible
我已經通過vcpkg
安裝了整個boost
v1.77.0 庫。 似乎嵌套的try/catch
塊是唯一的解決方案。
在外面創建變量。 如果你之后使用它,它也可能會拋出異常,那你為什么要忽略這些呢?
無論如何,您當然可以將其存儲在一些 singleton 容器類型(任何智能指針或optional
)中:
#include <boost/interprocess/ipc/message_queue.hpp>
#include <iostream>
#include <optional>
namespace ipc = boost::interprocess;
static inline constexpr auto g_szPipeName = "Test";
static inline constexpr std::string_view g_szMsgReady[6] = {"READY"};
int main()
{
std::optional<ipc::message_queue> mq;
try
{
mq.emplace(ipc::open_only, g_szPipeName);
mq->send(g_szMsgReady, sizeof(g_szMsgReady), 0);
} catch (const ipc::interprocess_exception& ex) {
std::cerr << ex.what() << std::endl;
return 255;
}
mq->send(g_szMsgReady, sizeof(g_szMsgReady), 0);
}
請注意,如果您的
g_szMsgReady
與我的一樣,您的sizeof(...)+1
超出范圍,導致 UB。
在我的盒子上打印:“沒有這樣的文件或目錄”(顯然我沒有創建命名隊列)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.