RAII and smart pointers in C++

后端 未结 6 1425
走了就别回头了
走了就别回头了 2020-11-21 23:45

In practice with C++, what is RAII, what are smart pointers, how are these implemented in a program and what are the benefits of using RAII with smart pointers?

6条回答
  •  无人共我
    2020-11-22 00:46

    Smart pointer is a variation of RAII. RAII means resource acquisition is initialization. Smart pointer acquires a resource (memory) before usage and then throws it away automatically in a destructor. Two things happen:

    1. We allocate memory before we use it, always, even when we don't feel like it -- it's hard to do another way with a smart pointer. If this wasn't happening you will try to access NULL memory, resulting in a crash (very painful).
    2. We free memory even when there's an error. No memory is left hanging.

    For instance, another example is network socket RAII. In this case:

    1. We open network socket before we use it,always, even when we don't feel like -- it's hard to do it another way with RAII. If you try doing this without RAII you might open empty socket for, say MSN connection. Then message like "lets do it tonight" might not get transferred, users will not get laid, and you might risk getting fired.
    2. We close network socket even when there's an error. No socket is left hanging as this might prevent the response message "sure ill be on bottom" from hitting sender back.

    Now, as you can see, RAII is a very useful tool in most cases as it helps people to get laid.

    C++ sources of smart pointers are in millions around the net including responses above me.

提交回复
热议问题