Skip to content

Instantly share code, notes, and snippets.

@slwu89
Created December 4, 2019 20:32
Show Gist options
  • Save slwu89/4b72c0f3262f3d0941b7332aea045ac6 to your computer and use it in GitHub Desktop.
Save slwu89/4b72c0f3262f3d0941b7332aea045ac6 to your computer and use it in GitHub Desktop.
checking that shared pointers are working right when mtple objects are sharing one resource, even when the first goes out of scope
//
// main.cpp
// test_simple
//
// Created by Sean Wu on 4/10/19.
// Copyright © 2019 Sean Wu. All rights reserved.
//
#include <memory>
#include <functional>
#include <iostream>
#include <vector>
class widget {
public:
static int id;
widget(std::shared_ptr<std::vector<int>> ptr) : my_p(ptr), myid(id++) {};
std::shared_ptr<std::vector<int>> my_p;
int myid;
};
int widget::id = 0;
int main(int argc, const char * argv[]) {
std::vector<widget*> widgets;
{
auto deleter = [](std::vector<int>* vptr){
std::cout << " --- deleting vptr at " << vptr << " --- \n";
delete vptr;
};
std::shared_ptr<std::vector<int>> p(new std::vector<int>{1,2,3,4,5}, deleter);
std::cout << " --- ref count: " << p.use_count() << " --- \n";
widgets.emplace_back(new widget(p));
std::cout << " --- ref count: " << p.use_count() << " --- \n";
widgets.emplace_back(new widget(p));
std::cout << " --- ref count: " << p.use_count() << " --- \n";
widgets.emplace_back(new widget(p));
std::cout << " --- ref count: " << p.use_count() << " --- \n";
}
for(auto& it : widgets){
std::cout << "widget: id " << it->myid << " pointing to " << it->my_p << " and ref count " << it->my_p.use_count() << "\n";
}
delete widgets[0];
delete widgets[1];
delete widgets[2];
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment