Created
October 25, 2021 06:58
-
-
Save xueliu/531689645a8cf9eda3e8d61bbc746c4c to your computer and use it in GitHub Desktop.
Memory leak with shared_ptr https://renyili.org/post/smart_ptr_mem_leak/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <memory> | |
#include <string.h> | |
#include <vector> | |
using namespace std; | |
struct Data | |
{ | |
char data[1000]; | |
~Data() { } | |
}; | |
struct Father | |
{ | |
Father() {} | |
// virtual | |
~Father() { } | |
}; | |
struct Child : Father | |
{ | |
Child() : Father() {} | |
~Child() {cout << "Child destructor" << endl;} | |
void create() | |
{ | |
weak_ptr = std::make_shared<Data>(); | |
} | |
std::weak_ptr<Data> weak_ptr; | |
}; | |
int main(int, char **) | |
{ | |
std::vector<Father *> vec; | |
for (int i = 0; i < 10; i++) | |
{ | |
Child *child_ptr = new Child(); | |
child_ptr->create(); | |
vec.push_back(child_ptr); | |
} | |
for (auto &itr : vec) | |
{ | |
delete itr; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment