Carry a tape recorder and practice humming or whistling the tune into it. A capella it until you get to a proper recording or composing implement.
I have no idea if that would work.
If it's just a melody and I'm near my keyboard it's the same thing as recording it, with the added bonus of being able to get any sound you can make with your mouth / surroundings.
Damn, I experience this every day of my life. It's almost heart breaking when I completely forget that awesome melody I'd thought up earlier in the day.
For times like that it helps to be able to sing the melody out in
sol-fa so you don't have to remember how it sounds as much as a bunch of short words to tell you how it sounds. Alternatively you can attempt to transpose it straight from you head onto somewhere so you don't need to remember. The downside to this is that it's very hard and takes a lot of practise before you're able to write it straight out without something to check with.
Sort of related, but do people find they get the best melodies and improvisations while in the shower? Pretty much every day without fail, when I'm in the shower I get a bitching song playing in my head, most parts as well, but since I shower before bed or late at night, never convert it into an idea. It also happens that once I leave the bathroom and try to start recording the idea fades fast.