C++ 如何正确传递zmq上下文(void*)?

C++ 如何正确传递zmq上下文(void*)?,c++,c,zeromq,void-pointers,C++,C,Zeromq,Void Pointers,我使用ZMQ的原生C库来编写我的应用程序(应用程序本身是用C++编写的)。ZMQ版本是4.04。我的问题是我有一个工厂类,它提供对zmq上下文的单例访问,这是由zmq\u ctx\u new()创建的无效指针。zmq上下文本身存储为静态成员变量,并提供getter方法来访问该变量的引用。类本身非常简单,下面是完整的代码: zmq\u ctx\u工厂.h #include <zmq.h> #include <cassert> class ZmqCtxFactory { p

我使用ZMQ的原生C库来编写我的应用程序(应用程序本身是用C++编写的)。ZMQ版本是4.04。我的问题是我有一个工厂类,它提供对zmq上下文的单例访问,这是由
zmq\u ctx\u new()
创建的无效指针。zmq上下文本身存储为静态成员变量,并提供getter方法来访问该变量的引用。类本身非常简单,下面是完整的代码:

zmq\u ctx\u工厂.h

#include <zmq.h>
#include <cassert>

class ZmqCtxFactory
{
public:
  static void* get_ctx()
  {
    assert (zmq_ctx_ != (void*) NULL);
    return &zmq_ctx_;
  }

  static bool is_initialized()
  {
    return is_initialized_;
  }

  static void init()
  {
    zmq_ctx_ = zmq_ctx_new ();
    is_initialized_ = true;
  }
private:
  static void* zmq_ctx_;
  static bool is_initialized_;
};
下面的问题是,在我的客户机代码中,下面会给出一个错误(错误代码14,错误地址)


但是如果我替换
ZmqCtxFactory::get_ctx()带有
zmq_ctx_new(),代码工作正常。如您所见,我有一个断言来确保上下文不为NULL,这意味着成功创建了ctx变量。(根据文档,如果创建失败,
zmq\u ctx\u new()
返回NULL)。我很困惑,为什么工厂返回的引用不起作用?

ZmqCtxFactory::get_ctx()
似乎返回指针的地址,而不是指针本身

试一试


问题在于
static void*get_ctx()
不返回引用,而是返回void指针的地址。将方法更改为以下后,代码工作正常:

static void*& get_ctx()
  {
    assert (zmq_ctx_ != (void*) NULL);
    return zmq_ctx_;
  }

我在发布后马上发现了同样的问题,将在7分钟内接受您的答案:)发布后,我重新阅读了您的问题,并想添加一条关于通过引用返回的备注。但当时你已经回答了这个问题:)。
void* context = ZmqCtxFactory::get_ctx();
assert (context != (void*) NULL);
socket_ = zmq_socket (context, ZMQ_SUB);
static void* get_ctx()
{
    assert (zmq_ctx_ != (void*) NULL);
    return zmq_ctx_; // instead of return &zmq_ctx_;
}
static void*& get_ctx()
  {
    assert (zmq_ctx_ != (void*) NULL);
    return zmq_ctx_;
  }