Back to TILs

C++ std::smart_ptr<void>

Date: 2024-11-02Last modified: 2024-11-03

Table of contents

class A {
public:
  explicit A( std::shared_ptr<void> ptr ) : mVoidPointer( ptr )
  {
    std::cout << "A constructor" << std::endl;
  }
  virtual ~A()
  {
    std::cout << "A destructor" << std::endl;
  }
  std::shared_ptr<void> object() const
  {
    return mVoidPointer;
  }

private:
  std::shared_ptr<void> mVoidPointer;
};

class B {
public:
  B()
  {
    std::cout << "B constructor" << std::endl;
  }
  void func()
  {
    std::cout << "B func" << std::endl;
  }
  virtual ~B()
  {
    std::cout << "B destructor" << std::endl;
  }
};
  auto b1 = std::make_shared<B>();
  std::cout << "b1.use_count = " << b1.use_count() << std::endl;

  auto a1 = std::make_shared<A>( b1 );
  std::cout << "b1.use_count = " << b1.use_count() << std::endl;

  std::shared_ptr<B> b2 = std::static_pointer_cast<B>( a1->object() );
  if( b2 ) {
    b2->func();
  }
  std::cout << "b1.use_count = " << b1.use_count() << std::endl;
  std::cout << "b2.use_count = " << b2.use_count() << std::endl;

  std::cout << "End of main scope" << std::endl;

Possible output

B constructor
b1.use_count = 1
A constructor
b1.use_count = 2
B func
b1.use_count = 3
b2.use_count = 3
End of main scope
A destructor
B destructor

References