错误在类文件中包装ZMQ C ++

时间:2016-04-27 03:38:13

标签: c++ pointers zeromq

我写了一个小类来用类文件包装C ++ ZMQ绑定,但是当我尝试调用send_message方法时,我看到以下错误:

terminate called after throwing an instance of zmq::error_t: Socket Operation on non-socket

实际上,我正在尝试将套接字存储在类中的指针中,然后在主文件中存储指向该类的指针。链被破坏在哪里?

以下是类文件中的相关代码:

zmq_client.cpp

class ZMQClient
{
zmq::socket_t *internal_socket;
public:
    ZMQClient (std::string conn);
    ~ZMQClient () {delete internal_socket;}
    void send_msg (const char * msg);
};

zmq_client.cpp

ZMQClient::ZMQClient (std::string conn)
{
    //Set the internal socket
    zmq::context_t context (1);
    zmq::socket_t socket (context, ZMQ_REQ);
    internal_socket=&socket;
    internal_socket->connect (conn);
}

void ZMQClient::send_msg (const char * msg)
{
//Convert the character array to zmq::message_t
...
internal_socket->send (request);
}

这是main.cpp文件中的相关代码:

#include "src/zmq_client.h"
ZMQClient *zmqo;

void func(const char * msg)
{
zmqo->send_msg(msg);
}

int main()
{
//Set up the outbound ZMQ Client
ZMQClient zout (OMQ_OBConnStr);
zmqo = &zout;
...
func(msg);
return 0;
}

1 个答案:

答案 0 :(得分:3)

下面:

internal_socket=&socket;

您正在存储临时变量的地址。您应该只是在类中按值存储套接字及其上下文:

class ZMQClient
{
    zmq::context_t context;
    zmq::socket_t internal_socket;

然后:

ZMQClient::ZMQClient(std::string conn)
    : context(1)
    , socket(context, ZMQ_REQ)
{
    socket.connect(conn);
}