r/cpp_questions • u/CommandShot1398 • 5d 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
u/MoTTs_ 5d ago edited 5d ago
It actually doesn't have to.
I think the missing piece of information is that, every object's "this" is ultimately implemented as an ordinary parameter/argument. Which means that when you write a member function signature, such as...
...this member function appears to us to take just one parameter, because that's what the source code shows. But in truth, the compiler is implicitly inserting an extra parameter for you. From the compiler's perspective, your member function is actually this...
And so in bind, it doesn't actually need to differentiate
thisfrom other arguments, becausethisreally is... just another argument.