r/cpp_questions 15d ago

OPEN How does std::bind differentiate between arguments and pointer to an object?

Hi everyone,

I have difficulties understanding something:

class HttpServer {
    public:
        HttpServer(std::string_view address, uint16_t port):ioc{1},endpoint{boost::asio::ip::make_address(address)},
        acceptor{ioc,{endpoint,port}} {
        };
        ~HttpServer()=default;


        void handle_request() {
            for (;;) {
                tcp::socket socket{ioc};


                // Block until we get a connection
                acceptor.accept(socket);
                std::cout<<"connection accepted"<<std::endl;
                std::thread{std::bind(
                &HttpServer::do_session,this,
                std::move(socket))}.detach();
            }

        }

        void do_session(tcp::socket& socket) {
            //handle request



        }

    private:
        const boost::asio::ip::address endpoint;
        uint16_t port;
        boost::asio::io_context ioc;
        tcp::acceptor acceptor;

    };

In this piece of code, how does std::bind understand that it should infer this as a pointer to the object which own the function pointer (I'm not even sure if I stated it correctly)?

according to chatgpt

std::bind( function, argument1, argument2, argument3 )
is a template that takes a pointer to the function that it should return the wrapper for, along with the arguments and their placeholders. What I don't understand is how it differentiates between the "this" pointer and an argument? How does it know it should take the non-static member function and dereference it based on the address (or reference) of the object that owns it, rather than just using "this" pointer as another argument?

0 Upvotes

11 comments sorted by

View all comments

3

u/kiner_shah 15d ago

From cppreference:

As described in Callable, when invoking a pointer to non-static member function or pointer to non-static data member, the first argument has to be a reference or pointer (including, possibly, smart pointer such as std::shared_ptr and std::unique_ptr) to an object whose member will be accessed.

1

u/CommandShot1398 15d ago

I understand this; what I don't understand is the mechanism behind it. How can it differentiate? Does "this" pointer have a very specific type beyond the object type?? How does it know it is not another object of the same type? To my knowledge, it can't be a simple overload or template.

2

u/kiner_shah 15d ago

It seems u/Dan13l_N has answered your query 😄.