Long-term memory is associated with the synthesis of proteins for the formation of neural connections. So that a person does not remember all the garbage that he dreamed, there are special substances that inhibit this process, and during sleep and some time after it, they are produced. But, apparently, they can be produced more or less, and depending on this, you will remember the dream or forget.
There is no exact answer yet, but there are some observations.
For example, dreams with the most emotional content often linger in the head. Also, the brain will preserve the memory of a dream for you if sleep is on the agenda that the brain has formed for you.
But the fact that it is difficult to distinguish your real dream from what you thought of when you woke up. It's just that when you wake up and the dream is already beginning to erode, in order to grab hold of it, you begin to comprehend it with the already rational part of the brain, and this distorts everything: there remains a small piece of sleep, hung with your thoughts and interpretations. Sorry, of course, that I was so bent.