C ++在地图中放置emplace()时防止Destructor调用

时间:2018-10-21 12:53:01

标签: c++ sockets move raii

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

我编写了一个类ConnectionHandler,该类处理从对accept()的调用创建的网络套接字。

此类在设计时考虑了RAII,当调用accept()时,将返回的套接字放入ConnectionHandler中,当超出范围时,析构函数将关闭套接字。

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

我在将这些ConnectionHandler嵌入到地图中时遇到了问题。

我这样做是为了使ConnectionHandler无法被复制(至少我相信我已经做到了),但是在调用std::map::emplace时,ConnectionHandler'调用s的析构函数(大概是删除沿行创建的临时对象),然后关闭套接字。

如您所见,这造成了一个问题,因为现在无法在程序的更下方使用套接字。

当将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类的样子(我知道,它不适用于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对象的析构函数中联接。

2 个答案:

答案 0 :(得分:5)

在您的move构造函数/赋值运算符中,您需要使从对象移动的对象无效。从对象移出后,析构函数仍将被调用。如果它们的套接字不为0,则析构函数仍将在fd上调用close。

答案 1 :(得分:1)

您的移动操作已损坏,因为它们留下两个引用同一套接字的对象。您需要将一个虚拟(无效)套接字值放置到移出的对象上,并在析构函数中进行检查。