当有一个所有者(std :: unique_ptr)但是其他对象需要对象的"句柄"时,C++ 11应该使用原始指针吗?

pau*_*ulm 2 pointers c++11

在以下情况中我似乎找到了很多代码:

class Thing
{
public:
   Thing() = default;
};

class Repo
{
public:
  Repo()
  {
     // Makes things..
     mThings.emplace_back( std::make_unique<Thing>() );
  } 

  // I find I need functions like this, 
  // a function which may return some record, 
  // or might return nullptr if there is no record.
  Thing* GetThing(int id)
  {
     // Might return nullptr, or might return
     return mThings[0].get();
  }

private:
  std::vector<std::unique_ptr<Thing>> mThings;
};
Run Code Online (Sandbox Code Playgroud)

Repo用于获取a 的对象Thing不拥有它,所以如果在这种情况下使用原始指针是否可接受?

将它强制为a std::shared_ptr并返回a 似乎是错误的,std::weak_ptr因为调用者知道如果GetThing不返回nullptr则该对象将存在,只要它确实存在.此外,所有权实际上并未共享.

class SomeObj
{
public:
  SomeObj(Repo& repo, int id)
   : mRepo(repo), mMyThing(nullptr), mId(id)
  {
     mMyThing = mRepo.GetThing(mId);
  }
private:
  Repo& mRepo;
  Thing* mMyThing;
  int mId;
};
Run Code Online (Sandbox Code Playgroud)

cub*_*l42 5

是的,纯指针就足够了.但是具有句柄(指针)Thing的对象必须假定被指向的对象将比它们寿命更长.