当你需要一个但只有一个参考时,创建一个假智能指针的最佳方法是什么?

Best way to create a fake smart pointer when you need one but only have a reference?

在您知道它没问题的情况下,伪造共享指针的最佳方法是什么?

#include <memory>

struct Target {
    bool ok() { return true; }
};

struct Monitor {
    // Take a shared pointer as we will be using it later
    Monitor(std::shared_ptr<Target> target)
        : target(target)
    { }

    bool check() {
        // Use the shared pointer we grabbed before
        return this->target->ok();
    }

    std::shared_ptr<Target> target;
};

// This function does not take a shared pointer because it does not
// hold on to the object after returning.
bool checkTargetOnce(Target& t)
{
    // We have to pass a shared_ptr to Monitor() because it wants to
    // keep a copy after the constructor returns.  But we know in this
    // case the Monitor instance won't be used after we return, so we
    // don't need a shared_ptr here - but we have to supply one anyway.

    Monitor m(t); // What should be put here?

    return m.check();
}

int main(void)
{
    Target t;
    checkTargetOnce(t);
    return 0;
}

把放shared_ptr的人打到*后,使用疯狂的(好吧,aliasing)构造函数shared_ptr:

template< class Y > 
shared_ptr( const shared_ptr<Y>& r, T *ptr );

这构造了一个 shared_ptrr 共享所有权但持有指针 ptr。现在我们可以反过来使 r 成为一个一无所有的 shared_ptr,即

Monitor m(std::shared_ptr<Target>(std::shared_ptr<Target>(), &t));

与使用空操作删除器的简单方法相比,这是有保证的 noexcept,并且由于不分配引用计数块而开销更小。


* 这一步是可选的。