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
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
> Is this safe?
Yes.
It's the analog of:
void test(some_type* const & A)
So, yes, it is perfectly fine.
Thanks
I discover one thing recently
There are one thing called "make_shared"
http://www.boost.org/doc/libs/1_43_0/libs/smart_ptr/make_shared.html
say this is a better choice than the semantic like this
shared_ptr<type_A> A(new type_A)
So we should choose make_shared over the old semantic anyway?
I am not really understand the way of make_shared work
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.
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
> 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
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.