c++ - "Attempting to reference a deleted function"

标签 c++ boost vector

这段代码在指定的行上给出了错误“attempting a reference a deleted function”。我的错误是什么,我该如何纠正?

#include <boost/asio.hpp>
#include <vector>

using boost::asio::ip::udp;

static char *port[] = { "54997", "34997", "57997", "58997" };
std::vector<udp::socket> sockets;

void getsockets()
{
    for (int i = 0; i < 4; i++)
    {
        boost::asio::io_service io_service;

        udp::resolver resolver(io_service);
        udp::resolver::query query(udp::v4(), "127.0.0.1", port[i]);

        udp::socket socket(io_service);
        socket.open(udp::v4());

        udp::endpoint sender_endpoint;
        socket.bind(sender_endpoint);
        sockets.push_back(socket);    //this line seems to be the one causing the error
    }
}

int main()
{

    getsockets();

    return 0;
}

最佳答案

两件事:

  1. io_service 在套接字的生命周期内由套接字使用,因此它不能是循环的局部变量。它必须与您的 vector 具有相同(或更长)的生命周期。

  2. udp::socket 不可复制。谈论复制套接字没有多大意义。但是它是可移动的,因此您可以将套接字直接放置到 vector 中,或者将其移动到 vector 中,例如:

    sockets.emplace_back( std::move(socket) );

注意。我对 boost::asio 不是特别熟悉,所以欢迎任何想要编辑此答案的人。

关于c++ - "Attempting to reference a deleted function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31929885/

相关文章:

c++ - 使用 std::function 作为成员函数,它捕获 `this` ,并在析构函数后从复制的 lambda 访问它

c++ - 具有 64 位基础整数的枚举

c++ - fork() 之后,如何在 for() 循环中继续运行 execve()?

c++ - 什么是分阶段 boost 库?

c++ - 从模板生成排列

c++ - vector <类*> 编译器错误 2143、4430、2238

python - 根据角度和速度计算交点

c++ - "I' m busy please wait"窗口 - 没有按钮

c++ - 如何使用 CMake 查找使用 VS 2017 编译的 Boost 文件系统库?

c++ - 分区 boost::range::transformed 范围适配器