Enable STL-style enable_shared_from_this (#1295)

This commit is contained in:
Steven Dee (Jōshin) 2024-09-15 19:32:13 -04:00 committed by GitHub
parent 6397999fca
commit ef62730ae4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 96 additions and 4 deletions

View file

@ -25,6 +25,7 @@
// #define ctl std
using ctl::bad_weak_ptr;
using ctl::enable_shared_from_this;
using ctl::make_shared;
using ctl::move;
using ctl::shared_ptr;
@ -66,6 +67,27 @@ struct Base
struct Derived : Base
{};
class SharedThis : public enable_shared_from_this<SharedThis>
{
struct Private
{
explicit Private() = default;
};
public:
SharedThis(Private)
{
}
static shared_ptr<SharedThis> create()
{
return make_shared<SharedThis>(Private());
}
};
class CanShareThis : public enable_shared_from_this<CanShareThis>
{};
int
main()
{
@ -241,6 +263,19 @@ main()
return 23;
}
{
// enable_shared_from_this allows shared pointers to self.
auto x = SharedThis::create();
auto y = x->shared_from_this();
if (x.use_count() != 2 || x.get() != y.get())
return 24;
auto z = new CanShareThis();
auto w = shared_ptr<CanShareThis>(z);
auto v = w->shared_from_this();
if (w.use_count() != 2 || w.get() != v.get())
return 25;
}
// TODO(mrdomino): exercise threads / races. The reference count should be
// atomically maintained.