Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same address, multiple shared_ptr counters, is it forbidden by C++ standard?

Suppose I have the need to do the following (This is just some imaginative code for discussion of the C++ standard, thus I won't discuss why I design it this way, so don't bother me with something like: your design is wrong.)

T* ptr = new T;
shared_ptr<T> p(ptr);
shared_ptr<T> q(ptr, SomeDeleterThatDoesnotDeleteButDoSomeOtherStuff());

Suppose the logic guarantees that p or some of its copies lives longer than all copies of q, so practically there won't be any problem. My question is, is it forbidden by C++ standard, e.g. explicitly stated as UB by C++ standard, for different shared_ptr counters to share the same address?

Thanks.

like image 780
Kan Li Avatar asked Jun 18 '12 09:06

Kan Li


1 Answers

If the first shared_ptr object is destroyed, then you get UB because objects using the second might access released object.

Since you made sure that your first shared_ptr object lives longer then the second, you do not get UB.

like image 175
BЈовић Avatar answered Oct 05 '22 21:10

BЈовић