79604370

Date: 2025-05-03 04:57:24
Score: 1
Natty:
Report link

Despite there are already some answers using side effect in ~Foo I add my own.

I have some smart pointer implementations in my current project and used static variable to count how many destructors was called.

struct Foo {
  static inline int foo_destroyed  = 0;

  ~Foo() {
     ++foo_destroyed;
   }
};

TEST_F(TestUniquePtr, Constructor)
{
  Foo::foo_destroyed = 0;
  Foo* foo = new Foo();
  {
    tom::unique_ptr<Foo> tmp(foo);
  }
  ASSERT_EQ(1, Foo::foo_destroyed);
}

Here is the examples of how I'm using it https://github.com/aethernetio/aether-client-cpp/blob/main/tests/test-ptr/test-ptr.cpp#L72

But as @Eljah mentioned in comments I thing it whould be better to count all living objects especially if you would try to implement shared_ptr in future.

struct Foo {
  static inline int foo_count  = 0;

  Foo(){
     ++foo_count;
  }
  ~Foo() {
     --foo_count;
   }
};

TEST_F(TestUniquePtr, Constructor)
{
  Foo::foo_count = 0;
  Foo* foo = new Foo();
  ASSERT_EQ(1, Foo::foo_count);
  {
    tom::unique_ptr<Foo> tmp(foo);
  }
  ASSERT_EQ(0, Foo::foo_count);
}

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @Eljah
  • Low reputation (1):
Posted by: bugdruhman