A general question regarding the correct way to implement a dictionary data structure
in any dictionary data structure there is an add_to_ds function which receives the data needed to insert as a parameter. the question is this:should the add_to_ds get the object it self (type T) and do the memory al开发者_如何学编程location,or should the add_to_ds get a pointer to object and just insert the pointer (type T*,whoever uses the DS does the memory allocation).
what is the right way do do it,and why ?
There isn't any generally right / wrong way to do it. If you trust the caller not to modify the memory, you're fine storing a pointer. If, however you don't specify this in your interface, you'll have to duplicate the memory.
- If you let them enter pointers, they will be responsible with freeing memory, not touching it etc
- If you don't trust them, you'll have to free memory, you'll have to return copies to stored items (otherwise if you return your pointer they might free it / alter it)
精彩评论