C++ - Check if pointer is pointing to valid memory (Can't use NULL checks here)

后端 未结 6 1389
名媛妹妹
名媛妹妹 2020-12-21 18:01

I am creating scripting language. When I allocate thing ,it\'s allocate the thing and returns the address and then I do whatever with it and then delete it. I can\'t contro

6条回答
  •  萌比男神i
    2020-12-21 18:48

    Detecting whether memory no longer is alive could be done e.g. by maintaining a set of known dead pointer. Any pointer you create gets added to an alive set, and when you delete the object you move the pointer to the dead set.

    The really tricky part will be reusing memory. What do you do when you want to reuse the same address for a different object? You can't tell by looking at the pointer, because the pointers look the same. So unless you never want to reuse memory, you'll have to change your requirements.

    1. One possible way would be an added field in the structure. I know you said you don't want that, but many comments already suggest this as the best solution, and I tend to concur.
    2. Another possible way would be an added layer of indirection, so that you don't really pass out pointers to objects but instead indices into a list of living objects or whatever.
    3. You might also consider reference counting and garbage collection. That way objects would only get deleted when no one refers to them any more. Quite a lot of work, but as a user of a scripting languages I'd expect it to provide garbage collection.

提交回复
热议问题