Reputation: 85
I have something like this:
void foo(){
Student *a0 = new Student();
Student *a1 = new Student();
Student *a2 = new Student();
Student *a3 = new Student();
}
I have another function
void foo2(){
Student* delStudent;
delStudent = ll.ReturnStudentToDelete(); //this function returns a pointer to delete student
delete delStudent ;
delStudent = NULL;
}
suppose, ll.ReturnStudentToDelete()
returns address of a2
, above code deletes this object. I want also to set pointer 'a2' to NULL. But I don't know how to retrieve a2 pointer so that to set it to NULL.
Currently I have 2 pointers (a2 and selStudent) which point to same object
Also, I was asked to use operator*() and operator->()
. But I didn't get that at all, so I try to do my best. Could you please post simple template example of how that may be implemented. I understand that above raw pointers are bad to use
Upvotes: 1
Views: 108
Reputation: 33854
Based on your code, since you do this:
void foo(){
Student *a0 = new Student();
...
}
Actually, you never store the pointers. In fact this means that when you call foo
you will instantly leak all of the memory you create, because you have not stored these pointers. Not only can the ll.ReturnStudentToDelete()
function not get the a2
pointer, it won't be able to get any relevant pointer.
You should start with seeing if you can avoid using a pointer. For example, perhaps your code could work like this:
Student someStudent;
...
someStudent.doSomething();
Or if you really do need a group of students:
std::vector<Student> groupOfStudents;
Upvotes: 3