Skip to content

Instantly share code, notes, and snippets.

@ktaka
Last active April 19, 2019 07:47
Show Gist options
  • Save ktaka/8a22d8b4518dcbddf8cf129e48a1d345 to your computer and use it in GitHub Desktop.
Save ktaka/8a22d8b4518dcbddf8cf129e48a1d345 to your computer and use it in GitHub Desktop.
Test of std::enable_shared_from_this
#include <memory>
#include <vector>
#include <iostream>
class Circle : public std::enable_shared_from_this<Circle> {
public:
void setRadius(double r) {
radius = r;
if (radius < 1.0) {
smallCircles.emplace_back(shared_from_this());
}
}
static void printSmallCircles() {
for (auto c: smallCircles) {
std::cout << "radius=" << c->radius << std::endl;
}
}
private:
double radius;
static std::vector<std::shared_ptr<Circle>> smallCircles;
};
std::vector<std::shared_ptr<Circle>> Circle::smallCircles;
int main()
{
auto a = std::make_shared<Circle>();
a->setRadius(1.2);
auto b = std::make_shared<Circle>();
b->setRadius(0.9);
auto c = std::make_shared<Circle>();
c->setRadius(0.1);
Circle::printSmallCircles();
std::cout << "a.use_count=" << a.use_count() << std::endl;
std::cout << "b.use_count=" << b.use_count() << std::endl;
std::cout << "c.use_count=" << c.use_count() << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment