RAII and smart pointers in C++

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

    void foo()
    {
       std::string bar;
       //
       // more code here
       //
    }
    

    No matter what happens, bar is going to be properly deleted once the scope of the foo() function has been left behind.

    Internally std::string implementations often use reference counted pointers. So the internal string only needs to be copied when one of the copies of the strings changed. Therefore a reference counted smart pointer makes it possible to only copy something when necessary.

    In addition, the internal reference counting makes it possible that the memory will be properly deleted when the copy of the internal string is no longer needed.

提交回复
热议问题