Boost logo

Boost :

Subject: Re: [boost] [smart_ptr] Interest in the missing smart pointer (that can target the stack)
From: Noah (duneroadrunner_at_[hidden])
Date: 2016-01-29 14:58:25


> Yes, you can make a shared_ptr that points at a stack object (by using a
> null deleter) but AFAIK this doesn't actually work as expected unless
> you can guarantee that no shared_ptr instances will survive destruction
> of the stack frame (ie. it is only used within the call chain and never
> copied outside of it).
>
> And it's way too easy to break that guarantee because it's not the
> semantics that shared_ptr was designed for.

I think Gavin is right. Consider this scenario:

class CA {
public:
     CA(int x) : m_x(x) {}
     int m_x;
};

CA* a_ptr = nullptr;
CA a2_obj(2);
{
     CA a_obj(1);
     a_ptr = &a_obj;
     a2_obj = (*a_ptr);
}
if (a_ptr) {
     a2_obj = (*a_ptr); // this is bad
} else {
     // this would have been better
}

A simple demonstration of a potential danger of raw pointers. But using
"registered" pointers:

mse::TRegisteredPointer<CA> a_ptr;
CA a2_obj(2);
{
     mse::TRegisteredObj<CA> a_obj(1); // a_obj is entirely on the stack
     a_ptr = &a_obj;
     a2_obj = (*a_ptr);
}
if (a_ptr) {
     a2_obj = (*a_ptr); // Fortunately we never got here because a_ptr
"knows" its target was destroyed.
     // In my current implementation, this would have thrown an exception.
} else {
     // Pheww. Better.
}

I'm not sure that "std::shared_ptrs coerced into targeting the stack"
would have helped here.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk