在向量中存储boost套接字

时间:2014-08-20 00:22:36

标签: c++ sockets boost vector boost-asio

继承代码。我收到以下错误:

In member function ‘void socks4Server::listener(int)’:
sock4.cpp:16:49: error: no matching function for call to ‘std::vector<boost::shared_ptr<boost::asio::basic_stream_socket<boost::asio::ip::tcp>>>::push_back(boost::asio::ip::tcp::socket*)’ sockets.push_back(new tcp::socket(io_service));         

代码:

#include <iostream>
#include <vector>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
using boost::asio::ip::tcp;
using namespace boost;
using namespace std;

class socks4Server{
public:
    boost::asio::io_service io_service;
    bool online;

    void listener(int port){
        tcp::acceptor accept(io_service,tcp::endpoint(tcp::v4(),port));
        vector<shared_ptr<tcp::socket> > sockets;
        while(online){
            sockets.push_back(new tcp::socket(io_service));
            cout<<"new socket thing";
        }
    }

    socks4Server(int port){
        online=true;
        std::thread listen(&socks4Server::listener,this,port);
        listen.detach();
    }
};

int main(){
    socks4Server server(8080);
}

1 个答案:

答案 0 :(得分:4)

没有从原始指针到共享指针的隐式转换,因此您无法直接将原始指针推送到共享指针的向量上。使用以下之一:

sockets.push_back(shared_ptr<tcp::socket>(new tcp::socket(io_service)));
sockets.push_back(make_shared<tcp::socket>(io_service));
sockets.emplace_back(new tcp::socket(io_service));  // C++11 or later

另外,请注意将stdboost转储到全局命名空间。两个名称空间中都定义了许多名称(例如shared_ptr),因此这种不加区别的污染可能会导致模糊不清。