Shared Pointers using std::shared_ptr

Creating a shared_ptr to this

Is it okay to create a shared_ptr from the this pointer?

Illustration representing computer hardware

No, creating a shared_ptr from the this pointer is almost always a mistake. Consider this example:

#include <memory>

class Example {
public:
  std::shared_ptr<Example> GetPtr() {
    return std::shared_ptr<Example>(this);
  }
};

int main() {
  Example e;
  auto ptr = e.GetPtr();
}

The issue here is that the shared_ptr does not own the object it's pointing to. The object e is owned by the main function, not by any shared_ptr.

When the shared_ptr ptr is destroyed, it will attempt to delete the Example object. But this object was not dynamically allocated, and is not owned by the shared_ptr. This leads to undefined behavior, likely a crash.

The same issue occurs if you try to create a shared_ptr from the this pointer inside a member function.

The correct way to create a shared_ptr that owns an Example object is:

#include <memory>

class Example {
 public:
  static std::shared_ptr<Example> Create() {
    return std::shared_ptr<Example>(
      new Example());  
  }

 private:
  Example() {}  // Private constructor
};

int main() { auto ptr = Example::Create(); }

Now, the shared_ptr returned by Create() has ownership of the dynamically allocated Example object. When ptr is destroyed, the Example object will be safely deleted.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved