# How to do gc without gc
---
Take C++ as a example
----
Usually we do things like this
```cpp
int main() {
int* A = new int;
free(A);
}
```
----
Sometimes we delete it to early
```cpp
int main() {
int* A = new int;
free(A);
cout << *A << endl;
}
```
> Undefine behavior
----
Sometimes we delete it to late
```cpp
int main() {
int* A = new int;
cout << *A << endl;
}
```
> Memory leak
---
Is is possible we prevent it?
----
## Reference counting
----
```cpp=
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.
----
```cpp=
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;
}
```
----
```cpp=
I burn!
end program
```
----
```cpp=
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!
```
----
```cpp=
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
```
{"metaMigratedAt":"2023-06-16T19:50:13.670Z","metaMigratedFrom":"Content","title":"How to do gc without gc","breaks":true,"contributors":"[{\"id\":\"d1772779-b7a0-43d5-923b-0f7edbff5f95\",\"add\":1784,\"del\":5}]"}