It was mention in a lecture that it is better to isolate a pointer or place it inside a data structure rather than use it directly. What are the benefits of this?
Never heard of this before. This is especially strange because you will usually pass around data structures as pointers. (IF we are talking about C here, that is).
Data structures, as the name implies, really are there for structuring data. Nothing else. (Again, if we are talking about C).
Manipulating pointers directly can be dangerous because you lack information on their usage and then you can expose your code to memory leaks, adress violation, ...
When you place it into a data structure it can hold others useful infos, the most common usage is smarts pointers with reference counting.
But it can have other usage. For example, imagine you want to send a message to an object. If you manipulate the pointer directly and you want to call a method on this object but the pointer is null you get a segfault. By using an intermediate structure you can provide a default object which will be used if there is no object. You can imagine plenty of other uses.
Isolate a pointer let you have more contol over the semantic of his utilisation.
If you manipulate the pointer directly and you want to call a method on this object but the pointer is null you get a segfault. By using an intermediate structure you can provide a default object which will be used if there is no object.
please can any one explain this with the help of the example.
Its about responsibility. A bare pointer has no responsibility. There can be several pointers pointing to the same bit of memory. Who is responsible for releasing that memory when it it no longer required? Well, its not the pointers, its the programmers. Nothing wrong with that, its C style programming.
When you encapsulate the pointer you hand over responsibility to the encapsulating object, so you don't have to think about it. It should be impossible to have memory leaks, segfaults etc however you use the class. If you have to think about what you're doing as a class user than the encapsulation isn't good enough.