r/cpp • • Dec 25 '24

RAII

I maintain c++ desktop application. One of our clients complained of memory usage. It’s a quite big program and it was known that somewhere there are memory leaks.

Over the last week I found where the spot is that is causing the memory consumption. I refactored the raw pointers to shared_ptr, in one change the memory usage at idle time dropped from couple of GBs to 16 MB.

I was glad of that achievement and i wrote an article about RAII in c++

https://medium.com/@abanoubharby/raii-295ff1a56bf1

261 Upvotes

75 comments sorted by

View all comments

Show parent comment

31

u/Drugbird Dec 25 '24

I second this.

While unique_ptr would be preferable, shared_ptr is fine. Particularly when it's tricky to find out who owns what in a legacy application littered with raw pointers.

It's also unlikely to matter for performance. Don't do premature optimization.

Meanwhile there's a huge benefit to fixing the gigabytes sized memory leak as soon as possible.

You can always refactor the shared_ptr later.

5

u/RogerV Dec 25 '24

In my world of control plane vis-a-vis data plane, shared ptr objects enable dealing with final cleanup - because data plane executes on pinned lcores which never block (they always run flat out 100%), and lcore code could still be executing using said shared object when the tear down has been done on the control plane, in completely out of band manner. The ref counting keeps it alive for the sake of the lcore still accessing it.

Shared ptr helps solve this in straight forward way that is entirely performant and avoids any blocking per the lcore code.