c++ - How to wrap a raw pointer into a shared_ptr and prevent shared_ptr from deleting the object? -


I need to wrap a raw pointer in a shared_ptr to pass the function. The function does not return once in any reference to the input object.

  {MyClass i; Shared_ptr & lt; MyClass & gt; P (& amp; i); F (p); / / BAD: shared_ptr will erase I}   

How to prevent shared_ptr by removing the referenced object?

As stated in the comments, type an empty deleter:

 < Code> #include & lt; Type_traits & gt; Template & lt; Typename T & gt; Struct empty_delete {empty_delete () / * noexcept * / {} template & lt; Typename u & gt; Empty_dellete (const_delete   

Examples of use:

  #include & lt; Iostream & gt; #include & lt; Memory & gt; Structure noise (noise () (std :: cout & lt; "living"   one (new noise); std: : Shared_ptr & lt; noise & gt; b (new noise); std :: unique_ptr & lt; noisy, empty_delete & lt; noisy & gt; & gt; c (new noise); std :: shared_ptr & LT; noise & gt; D (new noise), empty_day & Lt; noise and (g);); (a) take; take; take care;); d; take;}   

output:

living alive
living alive
living
taking ... dead =


taking ... dead
caught Got it.
Taking ...
Detected.

Of course, this example is leaked memory.

Comments

Popular posts from this blog

excel vba - How to delete Solver(SOLVER.XLAM) code -

github - Teamcity & Git - PR merge builds - anyway to get HEAD commit hash? -

ios - Replace text in UITextView run slowly -