Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Is there a way to copy from shared_ptr<Widget> to shared_ptr<const Widget>? I think not, which would make one of the entries in that table completely impossible to use.


Why not? In fact shared_ptr even has an aliasing constructor that allows you to refer an pointer whose lifetime is tied to an unrelated shared_ptr.

Of course the only sane use case is that that unrelated shared_ptr will definitely outlive that other pointer. But you get the idea, shared_ptr is incredibly flexible.


const_pointer_cast should do the job.


That's for the reverse (unsafe) conversion. A shared ptr can always be implicitly converted to a shared ptr to const. In fact a shared_ptr<T> can always be implicitly converted to a shared_ptr<T2> as long as T* is convertible to T2*. So for example derived to base and anything to void are allowed.


Do they then share the reference count, or can you get in trouble by going out of scope in the wrong order?


They will share the same reference count. In fact you can make two shared_ptrs to arbitrary types share the same reference count (although in this case there is no implicit conversion and you need to use the explicit aliasing constructor); it is useful for interior pointers for example.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: