Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) C++0x std::unique_ptr

 

std::unique_ptr is an C++0x STL uncopyable smart pointer.

 

#include <cassert>
#include <memory>

struct Test { int m_x; };

int main()
{
  {
    std::unique_ptr<Test> p; //Uninitialized pointer
    //assert(p);  //Good: uninitialized pointer is detected
    //p->m_x = 3; //Bad: results in an access violation
  }
  {
    std::unique_ptr<Test> p(new Test);
    p->m_x = 3; //OK
  }
  {
    std::unique_ptr<Test> p;
    p.reset(new Test);
    p->m_x = 3; //OK
  }
  {
    std::unique_ptr<Test> p(new Test);
    //std::unique_ptr<Test> q(p); //std::unique_ptr cannot be copied
  }
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict