Should I use std::shared pointer to pass a pointer?

前端 未结 5 765
醉话见心
醉话见心 2021-02-04 02:18

Suppose I have an object which is managed by an std::unique_ptr. Other parts of my code need to access this object. What is the right solution to pass the pointer?

5条回答
  •  北海茫月
    2021-02-04 02:37

    Since the question update, I'd prefer:

    1. std::reference_wrapper<> as suggested by Richard Hodges, so long as you don't require the option of NULL values.

      Note that your use case does seem to require a default constructor though, so this is out unless you have some public static instance to use as default.

    2. some custom not_your_pointer type with the required semantics: default-constructable, copyable and assignable, convertible from unique_ptr and non-owning. Probably only worthwhile if you're using it a lot though, since writing a new smart pointer class requires some thought.

    3. if you need to handle dangling references gracefully, use std::weak_ptr and change ownership to a shared_ptr (That is, only one shared_ptr exists: there's no ambiguity about ownership and object lifetime is unaffected)


    Before the question update, I preferred:

    1. indicate that ownership is not transferred by passing a reference:

      void foo(T &obj); // no-one expects this to transfer ownership
      

      called as:

      foo(*ptr);
      

      you do lose the ability to pass nullptr though, if that matters.

    2. indicate that ownership is not transferred by explicitly prohibiting it:

      void foo(std::unique_ptr const &p) {
          // can't move or reset p to take ownership
          // still get non-const access to T
      }
      

      this is clear, but does expose your memory management policy to the callee.

    3. pass a raw pointer and document that ownership should not be transferred. This is the weakest and most error prone. Don't do it.

提交回复
热议问题