On Sat, Jan 30, 2016 at 9:07 PM, Michael Marcin
On 1/29/2016 3:27 PM, Emil Dotchevski wrote:
int main() { foo local; shared_ptr<foo> pl(&local,null_deleter()); .... do_something(p); .... assert(pl.unique()); }
Does it look less scary now?
No, it still just looks like the coder wants job security to me.
I understand that the goal of the snippet is to get a handle to 'local' which can be stored and later invalidated and this code is abusing shared_ptr for that purpose but it's completely wrong.
See "Smart Pointer Programming Techniques", www.boost.org/doc/libs/release/libs/smart_ptr/sp_techniques.html#static "The same technique works for any object known to outlive the pointer." It's wrong for the same reason you don't write operator==() to test for
equality and operator!=() to compute prime factorization.
Not the same thing at all. Consider this: if( shared_ptr<foo> sp=wp.lock() ) { //use sp } If you put this code inside the do_something function, it won't compute prime factorization, it'd work as expected regardless of whether the object referred to by wp happens to use null_deleter or not. Yes, you can write code that leads to undefined behavior, and yes you shouldn't be using null_deleters left and right, but this is valid technique when using shared_ptr. Emil