I\'ve been mulling over use of unique_ptr
vs shared_ptr
vs own_solution
. I\'ve discounted the latter as I\'ll almost certainly get it
So I suppose what I'm looking for is a deferencable weak_ptr that cannot be converted into a shared_ptr.
You could hand out your one little helper class:
template
class NonConvertibleWeakPtr
{
public:
NonConvertibleWeakPtr(const std::shared_ptr& p) : p_(p) {}
... // other constructors / assignment operators
bool expired() const { return p_.expired(); }
T* operator->() const { return get(); }
T& operator*() const { return *get(); }
private:
T* get() const { return p_.lock().get(); }
private:
std::weak_ptr p_;
};
This is slightly better than a raw pointer, because you can check if your pointer is still valid.
Example usage:
std::shared_ptr sp = std::make_shared(5);
{
NonConvertibleWeakPtr wp(sp);
if(!wp.expired()) {
std::cout << *wp << std::endl;
}
}
However a user can still misuse it for example with std::shared_ptr
, but it takes a bit more criminal energy.