如何避免使用shared_ptr悬空指针?

nav*_*jan 1 c++ memory-management stl smart-pointers c++11

我有一个类,其对象指针将作为键/数据添加到多个 std::map/std::unordered_map/hash(内部实现)中。为了自动删除对象,我使用了 shared_ptr。

我使用shared_ptr only类设计了我的类。

现在我想确保将来没有人这样做:

#include <memory>
#include <string>

class A {
 protected:
   struct this_is_private;

 public:
   explicit A(const this_is_private &) {}
   A(const this_is_private &, ::std::string, int) {}

   template <typename... T>
   static ::std::shared_ptr<A> create(T &&...args) {
      return ::std::make_shared<A>(this_is_private{0},
                                   ::std::forward<T>(args)...);
   }

 protected:
   struct this_is_private {
       explicit this_is_private(int) {}
   };

   A(const A &) = delete;
   const A &operator =(const A &) = delete;
};


::std::map<A*, int> m_error;
::std::map<::std::shared_ptr<A>, int> m_ok;

::std::shared_ptr<A> foo()
{
   ::std::shared_ptr<A> temp = A::create();

   A * obj_ptr = temp.get(); 
   m_error.insert(pair<A*, int>(obj_ptr, 10)); //How to make sure no one do this in future
   m_ok.insert(pair<::std::shared_ptr<A>, int>(temp,10)); //ok
}
Run Code Online (Sandbox Code Playgroud)

eer*_*ika 5

如何避免使用shared_ptr悬空指针?

通过根本不存储指向对象的裸指针(也不是引用或迭代器),或确保此类指针的生命周期短于共享指针的生命周期。后者的正确性不像前者的正确性那么容易证明。

如何确保将来没有人[存储裸指针]

除了完全封装对对象的访问之外,C++ 语言中没有任何功能可以阻止获取对象的地址并将其存储。获取地址的程序员始终有责任确保生命周期是 - 并且将来是 - 他们所期望的。改变对象生命周期的程序员有责任确保没有任何事情依赖于改变的生命周期。

有一些编程语言被设计成不让程序员直接访问对象的地址,从而使此类错误成为不可能。C++ 不是这些语言之一。