mercredi 6 mars 2019

Referring to a "std::unique_ptr" that you don't own (use a raw pointer?)

Typically if you are using a std::shared_ptr to point to an object and you want to create another pointer to that object that does not share ownership you would create a std::weak_ptr.

// Create a shared pointer to own the object
std::shared_ptr<int> p = std::make_shared<int>(42);

// Create a weak pointer (that does not own the object)
std::weak_ptr<int> q(p);

// Use the weak pointer some time later
if (std::shared_ptr ptr = q.lock()) {
  // use *ptr
}

My question is, how do you do this when it comes to std::unique_ptr?

Using a unique pointer ensures that the current resource is owned exclusively by the std::unique_ptr itself. But what if I want to create a pointer to the same resource that does not own that resource? I can't use a std::weak_ptr because weak pointers are designed to work with the reference count from a std::shared_ptr. Would I just use a raw pointer here? Or is there a better alternative?

// Create a unique pointer to own the object
std::unique_ptr<int> p = std::make_unique<int>(42);

// Create a non-owning pointer to the same object
// Is this really the best way?
int* q = p.get();

// Use the pointer some time later
if (q != nullptr) {

  // Imagine this may be multithreaded...
  // what happens if p.reset() is called by another thread while the current thread is RIGHT HERE.

  // use *q
}

The only way I can think of creating a non-owning pointer to an object owned by a std::unique_ptr would be to use a raw pointer, but as you can see from the code above this may cause issues in threaded applications. Is there a better way to achieve the same goal?

Aucun commentaire:

Enregistrer un commentaire