下面这种情况我好像找了挺多代码:
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/