What is the difference between Boost smart pointers and std smart pointers?

前端 未结 3 1189
被撕碎了的回忆
被撕碎了的回忆 2021-02-19 09:24

So, I\'d like to use smart pointers instead of raw and almost every topic on SO says about Boost library. But std has such things as std::auto_ptr and std::sh

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-19 10:06

    Well, std::shared_ptr and boost:shared_ptr are both reference counting pointers. Instead std::auto_ptr works very differently. The difference between std::shared_ptr and boost:shared_ptr is very small and mostly historically. Before C++11 there was no std::shared_ptr and only boost:shared_ptr. When C++11 was designed, they took boost:shared_ptr as a model.

    All your mentioned smart pointers have in common that they have their own mechanism to make sure that the lifetime management for points is done correctly. auto_ptr works so that if you have multiple instances of an auto_ptr then only one of them contains a pointer to the real object. Whenever you create an auto_ptr from another auto_ptr, then the new one will point to the object and the old one to NULL. On the other hand with shared_ptr there can be multiple shared_ptr instances that share the same object, only when the last one goes out of scope, only then the object is deleted..

    In C++11 there is a similar pointer type to std::auto_ptr, namely std::unique_ptr, but there are some important differences, see also std::auto_ptr to std::unique_ptr.

    References:

    • http://www.cplusplus.com/reference/std/memory/auto_ptr/
    • http://en.cppreference.com/w/cpp/memory/shared_ptr
    • http://www.boost.org/doc/libs/1_52_0/libs/smart_ptr/shared_ptr.htm
    • http://en.cppreference.com/w/cpp/memory/unique_ptr

提交回复
热议问题