(C++) SmartPointerExample1
February 24, 2017 · View on GitHub
(C++) SmartPointerExample1
Technical facts
Operating system(s) or programming environment(s)
Lubuntu 15.04 (vivid)
Qt Creator 3.1.1
- G++ 4.9.2
Libraries used:
STL: GNU ISO C++ Library, version
4.9.2
Qt project file: ./CppSmartPointerExample1/CppSmartPointerExample1.pro
TEMPLATE = app CONFIG += console CONFIG -= app_bundle CONFIG -= qt QMAKE_CXXFLAGS += -std=c++11 -Wall -Wextra -Werror SOURCES += main.cpp win32 { INCLUDEPATH += ../../Libraries/boost_1_54_0 }
./CppSmartPointerExample1/main.cpp
#include <cassert> #include <memory> #include <boost/scoped_ptr.hpp> #include <boost/shared_ptr.hpp> struct Test { int m_x; }; int main() { { std::unique_ptr<Test> p; assert(!p); p->m_x = 42; //Danger: uninitialized pointer not detected by std::unique_ptr } { std::shared_ptr<Test> p; assert(!p); p->m_x = 42; //Danger: uninitialized pointer not detected by std::shared_ptr } { boost::shared_ptr<Test> p; assert(!p); p->m_x = 42; //Good: uninitialized pointer detected by boost::shared_ptr } { boost::scoped_ptr<Test> p; assert(!p); p->m_x = 42; //Danger: uninitialized pointer not detected by boost::scoped_ptr } }