Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) StdUnique_ptrExample1

 

Cpp11Qt CreatorLubuntu

 

std::unique_ptr example 1: basics is a std::unique_ptr example.

 

Technical facts

 

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: ./CppStdUnique_ptrExample1/CppStdUnique_ptrExample1.pro

 

TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
CONFIG -= qt

SOURCES += main.cpp

#
#
# Type of compile
#
#

CONFIG(release, debug|release) {
  DEFINES += NDEBUG NTRACE_BILDERBIKKEL
}

QMAKE_CXXFLAGS += -std=c++11 -Wall -Wextra -Weffc++

unix {
  QMAKE_CXXFLAGS += -Werror
}

#
#
# Boost
#
#

win32 {
  INCLUDEPATH += \
    ../../Libraries/boost_1_54_0
}

 

 

 

 

 

./CppStdUnique_ptrExample1/main.cpp

 

#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
  }
  {
    std::unique_ptr<Test> p(new Test);
    std::shared_ptr<Test> q(p.release()); //Transfer ownership
    assert(!p);
    assert(q);
  }
}

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml