Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is implementing RAII via constructors and destructors considered bad 'Modern C++'?

Tags:

c++

c++11

raii

With the advent of smart pointer in C++, is manually implementing RAII via constructors and destructors considered bad 'modern C++' practice? Or are there applications where this is still relevant?

like image 436
Izzo Avatar asked Nov 30 '25 03:11

Izzo


1 Answers

Memory, via allocation, isn't the only kind of Resource that can be Acquired, so pointers aren't the only kind of beast that RAII is for.

Consider, for instance, a scoped lock:

template <class Lockable>
class lock_guard {
    Lockable& lck;
public:
    lock_guard(Lockable& lck)
        : lck(lck)
    {
        lck.lock();
    }

    ~lock_guard()
    {
        lck.unlock()
    }
};

No pointers. Still RAII. Still shiny, modern, and super useful.

like image 73
Barry Avatar answered Dec 01 '25 18:12

Barry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!