Compartilhar via


Como: criar e usar instâncias weak_ptr

Às vezes, um objeto deve armazenar uma maneira de acessar o objeto subjacente de um shared_ptr sem fazer com que a contagem de referência seja incrementada. Normalmente, essa situação ocorre quando você tem referências cíclicas entre shared_ptr instâncias.

O melhor design é evitar a propriedade compartilhada de ponteiros sempre que possível. No entanto, se você precisar ter a propriedade compartilhada de shared_ptr instâncias, evite referências cíclicas entre elas. Quando as referências cíclicas forem inevitáveis ou até mesmo preferíveis por algum motivo, use weak_ptr para dar a um ou mais proprietários uma referência fraca a outro shared_ptr. Usando um weak_ptr, você pode criar um shared_ptr que se une a um conjunto existente de instâncias relacionadas, mas somente se o recurso de memória subjacente ainda for válido. Um weak_ptr em si não participa da contagem de referência e, portanto, não pode impedir que a contagem de referência vá para zero. No entanto, você pode usar um weak_ptr para tentar obter uma nova cópia do shared_ptr com o qual foi inicializado. Se a memória já foi deletada, o operador bool de weak_ptr retorna false . Se a memória ainda for válida, o novo ponteiro compartilhado incrementa a contagem de referência e garante que a memória será válida enquanto a variável shared_ptr permanecer no escopo.

Exemplo

O exemplo de código a seguir mostra um caso em que weak_ptr é usado para garantir a exclusão adequada de objetos que possuem dependências circulares. Ao examinar o exemplo, suponha que ele foi criado somente depois que soluções alternativas foram consideradas. Os objetos Controller representam algum aspecto de um processo de máquina e operam independentemente. Cada controlador deve poder consultar o status dos outros controladores a qualquer momento, e cada um contém um vector<weak_ptr<Controller>> privado para essa finalidade. Cada vetor contém uma referência circular e, portanto, weak_ptr instâncias são usadas em vez de shared_ptr.

#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

class Controller
{
public:
   int Num;
   wstring Status;
   vector<weak_ptr<Controller>> others;
   explicit Controller(int i) : Num(i), Status(L"On")
   {
      wcout << L"Creating Controller" << Num << endl;
   }

   ~Controller()
   {
      wcout << L"Destroying Controller" << Num << endl;
   }

   // Demonstrates how to test whether the
   // pointed-to memory still exists or not.
   void CheckStatuses() const
   {
      for_each(others.begin(), others.end(), [](weak_ptr<Controller> wp) {
         auto p = wp.lock();
         if (p)
         {
            wcout << L"Status of " << p->Num << " = " << p->Status << endl;
         }
         else
         {
            wcout << L"Null object" << endl;
         }
      });
   }
};

void RunTest()
{
   vector<shared_ptr<Controller>> v{
       make_shared<Controller>(0),
       make_shared<Controller>(1),
       make_shared<Controller>(2),
       make_shared<Controller>(3),
       make_shared<Controller>(4),
   };

   // Each controller depends on all others not being deleted.
   // Give each controller a pointer to all the others.
   for (int i = 0; i < v.size(); ++i)
   {
      for_each(v.begin(), v.end(), [&v, i](shared_ptr<Controller> p) {
         if (p->Num != i)
         {
            v[i]->others.push_back(weak_ptr<Controller>(p));
            wcout << L"push_back to v[" << i << "]: " << p->Num << endl;
         }
      });
   }

   for_each(v.begin(), v.end(), [](shared_ptr<Controller> &p) {
      wcout << L"use_count = " << p.use_count() << endl;
      p->CheckStatuses();
   });
}

int main()
{
   RunTest();
   wcout << L"Press any key" << endl;
   char ch;
   cin.getline(&ch, 1);
}
Creating Controller0
Creating Controller1
Creating Controller2
Creating Controller3
Creating Controller4
push_back to v[0]: 1
push_back to v[0]: 2
push_back to v[0]: 3
push_back to v[0]: 4
push_back to v[1]: 0
push_back to v[1]: 2
push_back to v[1]: 3
push_back to v[1]: 4
push_back to v[2]: 0
push_back to v[2]: 1
push_back to v[2]: 3
push_back to v[2]: 4
push_back to v[3]: 0
push_back to v[3]: 1
push_back to v[3]: 2
push_back to v[3]: 4
push_back to v[4]: 0
push_back to v[4]: 1
push_back to v[4]: 2
push_back to v[4]: 3
use_count = 1
Status of 1 = On
Status of 2 = On
Status of 3 = On
Status of 4 = On
use_count = 1
Status of 0 = On
Status of 2 = On
Status of 3 = On
Status of 4 = On
use_count = 1
Status of 0 = On
Status of 1 = On
Status of 3 = On
Status of 4 = On
use_count = 1
Status of 0 = On
Status of 1 = On
Status of 2 = On
Status of 4 = On
use_count = 1
Status of 0 = On
Status of 1 = On
Status of 2 = On
Status of 3 = On
Destroying Controller0
Destroying Controller1
Destroying Controller2
Destroying Controller3
Destroying Controller4
Press any key

Como um experimento, modifique o vetor others para ser um vector<shared_ptr<Controller>> e, na saída, observe que nenhum destruidor é invocado quando RunTest retorna.

Confira também

Ponteiros inteligentes (C++ moderno)