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

标签 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;
};

使用 Repo 获取 Thing 的对象并不拥有它,那么在这种情况下使用原始指针是否可以/可以接受?

将它强制为 std::shared_ptr 并返回 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;
};

最佳答案

是的,纯指针就够了。但是,具有指向 Thing 的句柄(指针)的对象必须假定所指向的对象将比它们活得更久。

关于pointers - 当只有一个所有者(std::unique_ptr)但其他对象需要该对象的 "handle"时,C++11 是否应该使用原始指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23549744/

相关文章:

c++ - 变量指针的成员函数没有绘制到 SDL_Surface?

c++ - 编译器添加的优化导致 "final"方法的不同行为

c - MCU 上的 RTC - 函数指针和回调

c++ - 从取消引用的指针返回原始指针

c++ - C++中调用类模板的函数模板

c++ - 删除 std::unique_ptr<Base> 容器中的派生类

C++ 11单例。静态变量是线程安全的吗?为什么?

c++ - std::function 的类型别名

c++ - 如何使用数组按引用对对象进行排序? (以一种不那么愚蠢/复杂的方式。)

c - 防止c中的文件中的字符被写出