If you could only safely log out when docked, how do you think people who explore for several months at a time get on?

As others said, you can safely log out while flying. That being said, to be absolutely safe I'd probably opt to log out while at least a few dozen LS away from the nearest body. Still, I've logged out in the middle of asteroid fields and never had a problem, so that's just me being cautious when it's possible.
Don't worry about your ship, everything should be fine when you relog.