我在使用以下函数调用时遇到了一些代码问题:
User::User(const Socket::SocketAddress& addr) {
address = addr;
_usersListBySession.insert(std::pair<uint32_t, std::shared_ptr<User>>(sessionID, std::shared_ptr<User>(this)));
assert(this->address == addr); // succeeds
_userListByAddress.insert(std::pair<Socket::SocketAddress, std::shared_ptr<User>>(addr, std::shared_ptr<User>(this)));
assert(this->address == addr); // fails
}
我通过这样做解决了这个问题:
User::User(const Socket::SocketAddress& addr) {
address = addr;
std::shared_ptr<User> user(this);
_usersListBySession.insert(std::pair<uint32_t, std::shared_ptr<User>>(sessionID, user));
assert(this->address == addr); // succeeds
_userListByAddress.insert(std::pair<Socket::SocketAddress, std::shared_ptr<User>>(addr, user));
assert(this->address == addr); // succeeds
}
我做了什么,为什么它会起作用?