Skip to content

Instantly share code, notes, and snippets.

@odeblic
Last active July 28, 2017 03:16
Show Gist options
  • Save odeblic/9dadf17214e7e47c0ac2c7f8d8f013eb to your computer and use it in GitHub Desktop.
Save odeblic/9dadf17214e7e47c0ac2c7f8d8f013eb to your computer and use it in GitHub Desktop.
Why we should be careful when deciding to use the factory function std::make_shared
#include <iostream>
#include <memory>
#include <list>
struct Heavy
{
char buffer[1024 * 1024 * 8];
};
std::list<std::weak_ptr<Heavy>> container;
int main()
{
std::cout << "start memory allocation using std::shared_ptr<T>(...)" << std::endl;
for (int i=0; i<1024; i++)
{
container.push_back(std::shared_ptr<Heavy>(new Heavy()));
}
std::cout << "process completed without any problem" << std::endl;
std::cout << "start memory allocation using std::make_shared<T>(new T(...))" << std::endl;
for (int i=0; i<1024; i++)
{
container.push_back(std::make_shared<Heavy>());
}
std::cout << "process completed... after probably freezing for long time!" << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment