(C++) StdUnique\_ptrExample1

January 11, 2018 · View on GitHub

 

 

 

 

 

(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:

  • STL STL: GNU ISO C++ Library, version 4.9.2

 

 

 

 

 

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);   } }