Condividi tramite


unique_ptr::release

Rilascia la proprietà del puntatore archiviato restituito al chiamante e imposta il valore del puntatore archiviato su nullptr.

pointer release();

Valore proprietà/Valore restituito

Restituisce il puntatore archiviato.

Note

Usare release per acquisire la proprietà del puntatore non elaborato archiviato da unique_ptr. Il chiamante è responsabile dell'eliminazione del puntatore restituito. unique-ptr è impostato sullo stato costruito in modo predefinito vuoto. È possibile assegnare un altro puntatore di tipo compatibile a unique_ptr dopo la chiamata a release.

Esempio

In questo esempio viene mostrato in che modo il chiamante della versione è responsabile dell'oggetto restituito:

// stl_release_unique.cpp
// Compile by using: cl /W4 /EHsc stl_release_unique.cpp
#include <iostream>
#include <memory>

struct Sample {
   int content_;
   Sample(int content) : content_(content) {
      std::cout << "Constructing Sample(" << content_ << ")" << std::endl;
   }
   ~Sample() {
      std::cout << "Deleting Sample(" << content_ << ")" << std::endl;
   }
};

void ReleaseUniquePointer() {
   // Use make_unique function when possible.  
   auto up1 = std::make_unique<Sample>(3);
   auto up2 = std::make_unique<Sample>(42);
   
   // Take over ownership from the unique_ptr up2 by using release
   auto ptr = up2.release();
   if (up2) {
      // This statement does not execute, because up2 is empty.
      std::cout << "up2 is not empty." << std::endl;
   }
   // We are now responsible for deletion of ptr.
   delete ptr;
   // up1 deletes its stored pointer when it goes out of scope.   
}

int main() {
   ReleaseUniquePointer();
}

Output del computer:

  

Requisiti

Intestazione: <memory>

Spazio dei nomi: std

Vedere anche

Attività

Procedura: creare e utilizzare istanze unique_ptr

Riferimenti

Classe unique_ptr

<memory>

Altre risorse

membri di unique_ptr

<memoria> membri