在以下情况中我似乎找到了很多代码:
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)