C++ 在地图中放置()时防止析构函数调用

C++ Prevent Destructor call when emplace()'ing in map

我有一个 class 来管理资源(网络套接字)。

我写了一个 class ConnectionHandler 来处理调用 accept().

创建的网络套接字

这个class是为RAII设计的,当调用accept()时,返回的套接字被放入ConnectionHandler,当它超出范围时,析构函数关闭套接字。

我还通过将它们保存在映射中来跟踪所有打开的 ConnectionHandler(将套接字地址 (IP:Port) 映射到对应于该地址的 ConnectionHandler ).

我遇到了问题 "emplacing" 这些 ConnectionHandler 进入了地图。

我已经做到了ConnectionHandler不能被复制(至少我相信我已经做到了),但是当调用std::map::emplace时,ConnectionHandler 的析构函数被调用(大概是为了删除沿线某处创建的临时对象)并关闭套接字。

如您所见,这会产生一个问题,因为现在无法在程序的后面使用套接字。

我有什么办法可以防止 ConnectionHandler 的析构函数在将其放入 std::map 时被调用?

这是 ConnectionHandler 的代码: 头文件:

class ConnectionHandler
{
    private:
        constexpr static long BUFFER_SIZE = 1 << 12;    // 4K Buffer

        SocketAddress peer;             // This is kept around to be able to produce clear exception messages when something goes wrong
        SocketFileDescriptor socket;    // using SocketFileDescriptor = int;

    public:
        ConnectionHandler() noexcept = delete;                                      // Default Constructor

        explicit ConnectionHandler(SocketFileDescriptor socket, const SocketAddress& socketAddress) noexcept;   // Value Constructor

        ConnectionHandler (ConnectionHandler&& handler) noexcept;                   // Move Constructor

        ConnectionHandler (const ConnectionHandler& handler) = delete;              // Delete Copy Constructor

        ConnectionHandler& operator= (ConnectionHandler&& handler) noexcept;        // Move Assignment Operator

        ConnectionHandler& operator= (const ConnectionHandler& handler) = delete;   // Delete Copy Assignment Operator

        ~ConnectionHandler();                                                       // Destructor

        void close() noexcept;                                                      // Allow the owner to manually close the socket if necessary

        void set_blocking (bool blocking) const;                                    // Make the socket either blocking or non-blocking

        friend std::ostream& operator<< (std::ostream& stream, const ConnectionHandler& handler);   // Receive data from the socket

        friend std::istream& operator>> (std::istream& stream, const ConnectionHandler& handler);   // Send data to the socket
};

和实施:

ConnectionHandler::ConnectionHandler(SocketFileDescriptor socket, const SocketAddress& socketAddress) noexcept: peer(socketAddress), socket(socket)
{
}

ConnectionHandler::ConnectionHandler(ConnectionHandler&& handler) noexcept: peer(std::move(handler.peer)), socket(handler.socket)
{
}

ConnectionHandler& ConnectionHandler::operator=(ConnectionHandler&& handler) noexcept
{
    this->peer = std::move(handler.peer);
    this->socket = handler.socket;
    return *this;
}

ConnectionHandler::~ConnectionHandler()
{
    if (this->socket > 0)   //  Check if the socket has been closed manually
                            //  Don't bother setting the socket to -1, the object is being destroyed anyway
    {
        std::cout << "Closing socket from destructor " << this->socket << std::endl;
        ::close(this->socket);
    }
}

void ConnectionHandler::close() noexcept
{
    std::cout << "Closing socket from close() " << this->socket << std::endl;   // Close the socket manually and indicate it is closed by setting it's value to -1
    ::close(this->socket);
    this->socket = -1;
}

[...]

这是 SocketAddress class 的样子(不适用于 IPv6,我知道):

class SocketAddress
{
    private:
        std::array<std::uint8_t, 4> ip;
        std::uint16_t port;

    public:
        friend void swap (SocketAddress& sa1, SocketAddress& sa2) noexcept;

        SocketAddress() noexcept;

        explicit SocketAddress(struct sockaddr_storage* sockaddrStorage);

        SocketAddress (const SocketAddress& address) = default;

        SocketAddress (SocketAddress&& address) noexcept = default;

        SocketAddress& operator= (SocketAddress address);

        friend bool operator< (const SocketAddress& lhs, const SocketAddress& rhs) noexcept;

        friend std::string to_string(const SocketAddress& address) noexcept;
};

最后,这是创建 ConnectionHandler 并将其放置在地图中的代码:

void Server::listenLoop()   // acceptLoop() would be a better name
{

    struct sockaddr_storage remoteAddr;

    while(!stop)    // stop is a std::atomic<bool>
    {
        [...]   // accept() connections in a loop

        SocketAddress address = SocketAddress(&remoteAddr);
        this->incomingSockets.emplace(std::make_pair(address, ConnectionHandler(childFileDesc, address)));
    }

    [...]
}

该函数在与主线程分离的线程上运行,该线程保存在 Server 对象中,并在 Server 对象的析构函数中加入。

在您的移动 constructor/assignment 运算符中,您需要使移动的对象无效。析构函数仍将在从对象移动时调用。如果他们的套接字不为 0,那么析构函数仍将在 fd 上调用 close。

你的移动操作被破坏了,因为它们让你有两个引用同一个套接字的对象。您需要将虚拟(无效)套接字值放入移出的对象,并在析构函数中检查它。