It can be hard to remember it, if you just write it down.
Sometimes you can play the right melody, or the right chords, but with the wrong rhythm, and it becomes . . . well, crummy.
What I used to do was record 'newly thought of songs' on cassette, which was a hassel . . . mikes, blank tape, etc . . .
(Yep I'm an OLD dude, eh?!)
Then I started recording sound bites on my computer. Again, a hassel: load the software, plug in, adjust volumes . . .
Now I just plug into my looper pedal; wham - bang: done.
You don't have to just use it as a looper, you can use it as a recording device, too.
I can record/save up to 6 hours or 99 tunes.
I've tried recording just my voice for a new tune, but I tend to hear melodies as full chords, and a simple vocal melody doesn't capture that . . . I want to hear the minors, majors, 9ths, 7ths, whatever . . . Of course, that doesn't help me too much if I'm driving down the road!
If I'm driving, then what I do is to mentally repeat the song, and hope that I don't change it too much by the time I finally get a chance to pick up my guitar.