Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cohabitation of boost::shared_ptr and std::shared_ptr

I want to use boost::log at some point, but I cannot pass a std::shared_ptr as a parameter, because the compiler (VS2010) cannot convert it into a boost::shared_ptr.

I don't really like the fact that they are aliens to one another.

Is there a safe and transparent way to convert one into the another, so as they don't stumble over each other?

I don't think it is duplicate of this question that states both are the same.

like image 780
Stephane Rolland Avatar asked Sep 07 '12 09:09

Stephane Rolland


People also ask

Should I use shared_ptr or Unique_ptr?

Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed. Use shared_ptr when you want multiple pointers to the same resource.

What is boost :: shared_ptr?

shared_ptr is now part of the C++11 Standard, as std::shared_ptr . Starting with Boost release 1.53, shared_ptr can be used to hold a pointer to a dynamically allocated array. This is accomplished by using an array type ( T[] or T[N] ) as the template parameter.

When should you use shared_ptr?

An object referenced by the contained raw pointer will not be destroyed until reference count is greater than zero i.e. until all copies of shared_ptr have been deleted. So, we should use shared_ptr when we want to assign one raw pointer to multiple owners. // referring to the same managed object.

Can shared_ptr be Nullptr?

A null shared_ptr does serve the same purpose as a raw null pointer. It might indicate the non-availability of data. However, for the most part, there is no reason for a null shared_ptr to possess a control block or a managed nullptr .


1 Answers

You could do it like this:

template<typename T>
boost::shared_ptr<T> make_shared_ptr(std::shared_ptr<T>& ptr)
{
    return boost::shared_ptr<T>(ptr.get(), [ptr](T*) mutable {ptr.reset();});
}

template<typename T>
std::shared_ptr<T> make_shared_ptr(boost::shared_ptr<T>& ptr)
{
    return std::shared_ptr<T>(ptr.get(), [ptr](T*) mutable {ptr.reset();});
}

EDIT: Note that this does not work with weak references to the source ptr. So be careful with those!

like image 189
ronag Avatar answered Oct 05 '22 13:10

ronag