Files
cppdraft_translate/cppdraft/util/smartptr/enab.md
2025-10-25 03:02:53 +03:00

3.2 KiB

[util.smartptr.enab]

20 Memory management library [mem]

20.3 Smart pointers [smartptr]

20.3.2 Shared-ownership pointers [util.sharedptr]

20.3.2.7 Class template enable_shared_from_this [util.smartptr.enab]

1

#

A class T can inherit from enable_shared_from_this to inherit the shared_from_this member functions that obtain a shared_ptr instance pointing to *this.

2

#

[Example 1: struct X: public enable_shared_from_this { };

int main() { shared_ptr p(new X); shared_ptr q = p->shared_from_this(); assert(p == q); assert(p.owner_equal(q)); // p and q share ownership} — end example]

namespace std {template class enable_shared_from_this {protected:constexpr enable_shared_from_this() noexcept; constexpr enable_shared_from_this(const enable_shared_from_this&) noexcept; constexpr enable_shared_from_this& operator=(const enable_shared_from_this&) noexcept; constexpr ~enable_shared_from_this(); public:constexpr shared_ptr shared_from_this(); constexpr shared_ptr shared_from_this() const; constexpr weak_ptr weak_from_this() noexcept; constexpr weak_ptr weak_from_this() const noexcept; private:mutable weak_ptr weak-this; // exposition only};}

3

#

The template parameter T of enable_shared_from_this may be an incomplete type.

🔗

constexpr enable_shared_from_this() noexcept; constexpr enable_shared_from_this(const enable_shared_from_this<T>&) noexcept;

4

#

Effects: Value-initializes weak-this.

🔗

constexpr enable_shared_from_this<T>& operator=(const enable_shared_from_this<T>&) noexcept;

5

#

Returns: *this.

6

#

[Note 1:

weak-this is not changed.

— end note]

🔗

constexpr shared_ptr<T> shared_from_this(); constexpr shared_ptr<T const> shared_from_this() const;

7

#

Returns: shared_ptr(weak-this).

🔗

constexpr weak_ptr<T> weak_from_this() noexcept; constexpr weak_ptr<T const> weak_from_this() const noexcept;

8

#

Returns: weak-this.