void test(std:shared_ptr<some_type> A) {.....}

would make a copy of a shared_ptr
what if we pass a shared_ptr into a function like

void test(std:shared_ptr<some_type> const &A) {.....}

Is this safe?

Thanks a lot

std::make_shared<> is just a wrapper over std::allocate_shared<> with the allocator defaulted to std::allocator<>.

Assuming there is a constructor A::A( int, const char*, double ) for A,

auto pa = std::make_shared<A>( 1, "hello", 22.8 ) ;

is more efficient when compared to

std::shared_ptr<A> pa( new A( 1, "hello", 22.8 ) ) ;

It requires only one memory allocation instead of two; storage for the objct and its shared reference count is allocated together.

Edited 5 Years Ago by vijayan121: n/a

Comments
Nice!
std::shared_ptr<A> pa = std::make_shared<A>( 1, "hello", 22.8 ) ;

This is more efficient, how about this?

std::shared_ptr<A>  pa = std::make_shared<A>() ;

;
also more efficient than old semantic?

if pass by const reference is safe

void test(std:shared_ptr<some_type> const &A) {.....}

why most of the examples are pass by value?
is it because the cause to copy the object of shared_ptr is very cheap?

Thanks

Edited 5 Years Ago by stereomatching: n/a

> how about this?
> std::shared_ptr<A> pa = std::make_shared<A>() ;
> also more efficient than old semantic?

Yes, and for the same reason. Requires A to have an accessible default constructor, though.


> is it because the cause to copy the object of shared_ptr is very cheap?

shared_ptr<> hs move constructors and move assignment operators; it is extremely efficient when the source of the copy or assignment is a temporary or is no longer needed. In many other cases, the compiler would be able to apply copy-elision.

Even if a copy has to be made, it is quite cheap (copy a pointer and increment a reference count) if concurrency is not involved. If not, there would be a quality of implementation issue.

std::shared_ptr<type> create()
{
  return std::make_shared<type>();
}

Is this a better choice?
Thanks

This question has already been answered. Start a new discussion instead.