Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) StdUnique_ptrExample2

 

Cpp11Qt CreatorLubuntu

 

std::unique_ptr example 2: custom deleter is a std::unique_ptr example that shows how to use a custom deleter (in this case boost::checked_delete) with auto and std::function

 

Technical facts

 

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: ./CppStdUnique_ptrExample2/CppStdUnique_ptrExample2.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_ptrExample2/main.cpp

 

#include <iostream>
#include <boost/checked_delete.hpp>
#include <boost/scoped_ptr.hpp>


struct MyClass
{
  MyClass() {}

  static void Deleter(const MyClass * const p) { boost::checked_delete(p); }

  private:
  ~MyClass() { std::cout << "Destructor" << '\n'; }
  friend void boost::checked_delete<>(MyClass* x);
  friend void boost::checked_delete<>(const MyClass* x);
};

int main()
{
  {
    //Use of auto and lambda expression
    const auto deleter
      = [](const MyClass * const p)
      {
        boost::checked_delete(p);
      };

    const std::unique_ptr<const MyClass, decltype(deleter)> p {
      new MyClass,deleter
    };
  }

  {
    //Use of std::function and static member function
    const std::function<void(const MyClass * const)> deleter = MyClass::Deleter;

    const std::unique_ptr<const MyClass, decltype(deleter)> p {
      new MyClass,deleter
    };
  }
}

/* Screen output

Destructor
Destructor
Press <RETURN> to close this window...

*/

 

 

 

 

 

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