Passing around boost::asio::ip::tcp::socket

前端 未结 2 1899
Happy的楠姐
Happy的楠姐 2021-01-22 05:40

Alright, this is my current code snippet:

namespace bai = boost::asio::ip;
bai::tcp::socket tcp_connect(std::string hostname, std::string port) {
    try {
              


        
相关标签:
2条回答
  • 2021-01-22 06:11

    The code:

    return socket;
    

    attempts to make a copy of socket to return, and then destroy the original socket when the function exits. Unfortunately, sockets cannot be copied (they manage an underlying operating system resource that must be closed, so the system must ensure only one reference to that resource exists, otherwise things would go badly wrong when the first copy went out of scope).

    As suggested in the other answer, you could use a pointer to return an object created on the heap (which should be managed either with a shared_ptr, or more efficiently if you are only using it in a single place a unique_ptr), or if you are using C++11 you could use the move constructor for the return value:

    return std::move (socket);
    

    This would avoid the necessity to use heap allocation and pointers, so is probably the preferable solution.

    0 讨论(0)
  • 2021-01-22 06:24

    socket can't be copied. Use a boost::shared_ptr<bai::tcp::socket> instead. If you could copy a socket you'd have all sorts of funny issues if you ended up with two socket instances representing the same underlying OS socket - so it makes sense that copying (and therefore return by value, pass by value) is not allowed.

    0 讨论(0)
提交回复
热议问题