mario.schlipf
mario.schlipf

Reputation: 1257

Usage of member variable referencing own instance

I am currently investigating code of a C++ library which is not written by me. The code seems to be a little bit ugly to me, but I have to admin that I am no C++ pro.

The Library has a class, lets call it ExampleClass, which has a member variable std::shared_ptr<ExampleClass> this_ec which is not set in the constructor, but seems to be set always when another object creates an instance of ExampleClass:

std::shared_ptr<ExampleClass> ec = std::make_shared<ExampleClass>(...);
ec->this_ec = ec;

Could it be that this is used to prevent garbage collection?

Upvotes: 1

Views: 88

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254471

Could it be that this is used to prevent garbage collection?

Yes, if by "garbage collection", you mean "automatic deletion". The object won't be deleted as long as at least one shared pointer exists, so this will keep the object alive at least until that pointer is reset or reassigned.

This rather defeats the purpose of using smart pointers, since it's now easy to leak objects by losing all external pointers to them. Tread carefully here.

A less error-prone way to make a shared pointer to the current object available within the class is to inherit from enable_shared_from_this<ExampleClass>, and obtain the pointer with shared_from_this(). This effectively stores a weak pointer, which doesn't prevent deletion.

Upvotes: 4

Related Questions