Take C++ as a example
Usually we do things like this
int main() {
int* A = new int;
free(A);
}
Sometimes we delete it to early
int main() {
int* A = new int;
free(A);
cout << *A << endl;
}
Undefine behavior
Sometimes we delete it to late
int main() {
int* A = new int;
cout << *A << endl;
}
Memory leak
Is is possible we prevent it?
int main() { std::shared_ptr<int> p = std::make_shared<int>(2); cout << *p << endl; //2 *p = 5; cout << *p << endl; //5 }
How it works?
by reference counting
Let's do a exam.
class test { public: test() {cout << "I burn!" << endl;} ~test() {cout << "I die!" << endl;} }; int main() { test* p = new test; cout << "end program" << endl; return 0; }
I burn! end program
class test { public: test() {cout << "I burn!" << endl;} ~test() {cout << "I die!" << endl;} }; int main() { std::shared_ptr<test> p = std::make_shared<test>(); cout << "end program" << endl; return 0; }
I burn!
end program
I die!
class test { public: test() {cout << "I burn!" << endl;} ~test() {cout << "I die!" << endl;} }; int main() { { std::shared_ptr<test> p = std::make_shared<test>(); } cout << "end program" << endl; return 0; }
I burn!
I die!
end program
we have a obj, count = 0
when value = obj, count++
when value is destroy, count--
when count == 0, free(obj)
Let's try to do it by ourself
https://code.sololearn.com/c2rR1h9G9ehg