【问题标题】:Using boost message_queue otuside try/catch block使用 boost message_queue otuside try/catch 块
【发布时间】:2022-01-20 22:48:27
【问题描述】:
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 块是唯一的解决方案。

【问题讨论】:

  • g_szPipeName 是否已经创建,即不为空?
  • @kiner_shah 它是一个constexpr 我在一个头文件中定义的,这个文件是Main.cppg_szPipeName 是在Main.h 中定义的

标签: c++ boost


【解决方案1】:

在外面创建变量。如果你之后使用它,它也可能会抛出异常,那你为什么要忽略这些呢?

无论如何,您当然可以将其存储在一些单例容器类型中(任何智能指针或optional):

Live On Coliru

#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 char const 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。

在我的盒子上打印:“没有这样的文件或目录”(显然我没有创建命名队列)

【讨论】:

  • sizeof(...)+1 越界”,我不明白。 g_sz 部分表示这是一个全局const char*。我不知道string_view 是什么。 C++ 不断添加新的东西。无论如何,您知道为什么声明 mq 会导致错误吗?
  • 哦,哎呀。我本来打算删除字符串视图。显然应该是char const x[]。并且该数组的大小已经包含定义的 NUL 字符
  • @demberto 与任何变量声明相同:如果它不是默认可构造的,则需要传递合适的构造函数参数。
猜你喜欢
  • 2019-12-04
  • 1970-01-01
  • 2010-12-15
  • 2011-07-09
  • 1970-01-01
  • 2016-05-21
  • 1970-01-01
  • 2016-05-04
  • 2010-10-31
相关资源
最近更新 更多