当你需要一个但只有一个参考时,最好的方法来创建一个虚假的智能指针?

Mal*_*ous 1 c++ smart-pointers c++11

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

T.C*_*.C. 5

冲压谁把一个人后shared_ptr*,用疯狂的(好吧,走样的)构造函数shared_ptr:

template< class Y > 
shared_ptr( const shared_ptr<Y>& r, T *ptr );
Run Code Online (Sandbox Code Playgroud)

这构造了shared_ptr共享所有权,r但保留了指针ptr.现在我们可以反过来做r一个shared_ptr没有任何东西,即

Monitor m(std::shared_ptr<Target>(std::shared_ptr<Target>(), &t));
Run Code Online (Sandbox Code Playgroud)

与使用no-op删除器的朴素方法相比,这是有保证的noexcept,并且由于不分配引用计数块而具有较少的开销.


*此步骤是可选的.