RAII and smart pointers in C++

后端 未结 6 1423
走了就别回头了
走了就别回头了 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:28

    The premise and reasons are simple, in concept.

    RAII is the design paradigm to ensure that variables handle all needed initialization in their constructors and all needed cleanup in their destructors. This reduces all initialization and cleanup to a single step.

    C++ does not require RAII, but it is increasingly accepted that using RAII methods will produce more robust code.

    The reason that RAII is useful in C++ is that C++ intrinsically manages the creation and destruction of variables as they enter and leave scope, whether through normal code flow or through stack unwinding triggered by an exception. That's a freebie in C++.

    By tying all initialization and cleanup to these mechanisms, you are ensured that C++ will take care of this work for you as well.

    Talking about RAII in C++ usually leads to the discussion of smart pointers, because pointers are particularly fragile when it comes to cleanup. When managing heap-allocated memory acquired from malloc or new, it is usually the responsibility of the programmer to free or delete that memory before the pointer is destroyed. Smart pointers will use the RAII philosophy to ensure that heap allocated objects are destroyed any time the pointer variable is destroyed.

提交回复
热议问题