Getting started
Literals
Basic type keywords
Operator precedence
Floating point arithmetic
Bit operators
Bit manipulation
Bit fields
Arrays
Flow control
const keyword
Loops
mutable keyword
friend keyword
keywords
Variable declaration keywords
auto keyword
Pointers
Type keywords (class, enum, struct, union)
Classes / structs
std::string
Enumeration
std::atomic<T>
std::vector
std::array
std::pair
std::map
std::unordered_map
std::set and std::multiset
std::any
std::variant
std::optional
std::integer_sequence
std::function
std::forward_list
std::iomanip
Iterators
Basic I/O
File I/O
Streams
Stream manipulators
Metaprogramming
Returning multiple values from a function
References
Polymorphism
Value and reference semantics
Function call by value vs. by reference
Copying vs assignment
Pointers to class / struct members
The this pointer
Smart pointers
Unions
Templates
Namespaces
Function overloading
Operator overloading
Lambdas
Threading
Value categories
Preprocessor
SFINAE
Rule of three, five and zero
RAII
Exceptions
Implementation-defined behavior
Special member functions
Random numbers
Sorting
Regular expressions
Perfect forwarding
Virtual member functions
Undefined behavior
Overload resolution
Move semantics
Pimpl idiom
Copy elision
Fold expressions
Unnamed types
Singleton
ISO C++ Standard
User-defined literals
Type erasure
Memory management
Explicit type conversions
RTTI
Standard library algorithms
Expression templates
Scopes
Atomic types
static assert
constexpr
Date and time with std::chrono
Trailing return type
Function template overloading
Common compile linker errors
Design patterns
Optimizations
Compiling and building
Type traits
One definition rule
Unspecified behavio
Argument dependent name lookup
Attributes
Internationalization
Profiling
Return type covariance
Non-static member functions
Recursion
Callable objects
Constant class member functions
C++ vs. C++ 11 vs C++ 17
Inline functions
Client server examples
Header files
Const correctness
Refactoring techniques
Parameter packs
Iteration
type deduction
C++ 11 memory model
Build systems
Concurrency with OpenMP
Type inference
Resource management
Storage class specifiers
Alignment
Inline variables
Linkage specifications
Curiusly recurring template pattern
Using declaration
Typedef and type aliases
Layout of object types
C incompatibilities
Optimization
Semaphore
Thread synchronization
Debugging
Futures and promises
More undefined behaviors
Mutexes
Recursive mutex
Unit testing
decltype
Digit separators
C++ Containers
Arithmetic meta-programming
Contributors

Getting a shared_ptr referring to this

suggest change

enable_shared_from_this enables you to get a valid shared_ptr instance to this.

By deriving your class from the class template enable_shared_from_this, you inherit a method shared_from_this that returns a shared_ptr instance to this.

Note: the object must be created as a shared_ptr in first place:

#include <memory>
class A: public enable_shared_from_this<A> {
};
A* ap1 =new A();
shared_ptr<A> ap2(ap1); // First prepare a shared pointer to the object and hold it!
// Then get a shared pointer to the object from the object itself
shared_ptr<A> ap3 = ap1->shared_from_this(); 
int c3 =ap3.use_count(); // =2: pointing to the same object

Note: you cannot call enable_shared_from_this inside the constructor.

#include <memory> // enable_shared_from_this

class Widget : public std::enable_shared_from_this< Widget >
{
public:
    void DoSomething()
    {
        std::shared_ptr< Widget > self = shared_from_this();
        someEvent -> Register( self );
    }
private:
    ...
};

int main()
{
    ...
    auto w = std::make_shared< Widget >();
    w -> DoSomething();
    ...
}

If you use shared_from_this() on an object not owned by a shared_ptr, such as a local automatic object or a global object, then the behavior is undefined. Since C++17 it throws std::bad_alloc instead.

Using shared_from_this() from a constructor is equivalent to using it on an object not owned by a shared_ptr, because the objects is possessed by the shared_ptr after the constructor returns.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents