所以我有一些代碼:爲什麼我不能返回nullptr std :: weak_ptr?
class Thing
{
public:
Thing() = default;
};
class DbOfThings
{
public:
DbOfThings() = default;
std::weak_ptr<Thing> GetEntry(int someKey) const
{
// returns a weak_ptr from mThings, or null if a Thing
// that has someKey was not found
return std::weak_ptr<Thing>(nullptr);
}
private
// Idea is that this object owns these things, but other objects can grab a thing from here - but the thing can be killed off at any time
std::vector<std::share_ptr<Thing>> mThings;
但這種失敗,編譯:
沒有已知的轉換爲參數1從 '的std :: nullptr_t' 到「常量 的std :: weak_ptr的& '
爲什麼?我是否願意讓其他對象擁有另一個錯誤所擁有的東西?這對於weak_ptr來說似乎是一個有效的用例。我該如何做這項工作?
似乎沒有這樣的構造,但你可以使用默認的:'返回{};' – zch
爲什麼要用'shared_ptr'而不是'unique_ptr'如果向量是擁有該對象的唯一的事情嗎? (或者你可以不爲'unique_ptr'擁有的對象創建'weak_ptr',即使弱指針不會導致指向對象的所有權發生變化?) – JAB
...哦,我明白了。因爲'shared_ptr'可以將'weak_ptr'作爲構造函數,允許指向唯一指針所擁有的對象的弱指針將需要終止唯一指針,儘管'shared_ptr'有一個'unique_ptr'構造函數,可以間接地做到這一點有奇怪的效果。 – JAB