Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 alternative to boost::checked_delete

As a heavy user of forward declarations, I enjoy my classes being complete at destruction. To ensure this, I make the destructor private and befriend boost::checked_delete:

#include <boost/checked_delete.hpp>

struct MyClass
{
  //MyClass's interface
  private:
  ~MyClass() { /* something */ }
  friend void boost::checked_delete<>(MyClass* x);
};

In C++11, std::default_delete also checks for completeness at destruction. Nevertheless, I could not implement the same behaviour as above:

#include <memory>

struct MyClass
{
  //MyClass's interface
  private:
  ~MyClass() { /* something */ }
  friend struct std::default_delete<MyClass>;
};

int main()
{
  //const std::shared_ptr<MyClass> d { 
  //  std::make_shared<MyClass>() 
  //}; //(1) Should compile?

  const std::shared_ptr<MyClass> d(
    new MyClass,std::default_delete<MyClass>()
  ); //(2) Does compile
}

I wonder

  1. How can I get the line marked (1) to compile? The use of std::make_shared is A Good Thing
  2. Is the line marked (2) really valid? It feels bad to explicitly specify the deleter

I am using GCC 4.8.0 and I checked with both -std=c++11 and -std=c++1y flags.

like image 515
richelbilderbeek Avatar asked Nov 11 '22 12:11

richelbilderbeek


1 Answers

Something like this should work:

struct wrapper;

struct MyClass
{
private:
    ~MyClass() { /* something */ }
    friend wrapper;
};

struct wrapper
{
    MyClass obj;
};

// ...

auto const tmp = std::make_shared<wrapper>();
std::shared_ptr<MyClass> p(tmp, &tmp->obj);
like image 77
Simple Avatar answered Nov 15 '22 07:11

Simple