简体   繁体   中英

Smart pointers in functions

This is strictly theoretical question. When project is based on smart pointers, so practically all classes use them to wrap their pointer members, is it a bad practise to pass ordinary pointers to member/not member functions? I mean, is it correct to have member functions like:

void Function(SomeClass* pSomeClass);

Or should it always be:

void Function(std::shared_ptr<SomeClass> pSomeClass);

I also wander if there are any important consequences (except standard const features) of passing const reference:

void Function(const std::shared_ptr<SomeClass>& pSomeClass)

What about situation when class is using std::unique_ptr to protect its members, and for example, pointer to its member is used in class private member function? Should it be wrapped too? Or should it be considered as design mistake?

If the function only needs the pointed-to object and it must always be a valid object, not null, pass the object by reference (const or non-const, depending on the usual rules).

If the function only needs the pointed-to object, or optionally null, pass by raw pointer (to const or non-const, as per the usual rules).

If the function needs to share ownership of the pointed-to object, pass the shared_ptr by value .

If the function needs to modify the shared_ptr handle to the object (eg reset ), pass the shared_ptr by non-const reference .

If the function needs to access information on the shared_ptr handle (such as use_count ), but should not modify the shared_ptr , pass the shared_ptr by const reference .

I think Herb Sutter has some good answers for that. There is a GotW about smart pointer usage, and a more recent presentation where he covers this. The new C++ Core Guidelines have a full section about smart pointer usage.

In a nutshell it all comes down "Take smart pointers as parameters only to explicitly express lifetime semantics" . If you pass a smart pointer, this should imply that you talk/participate in ownership, either shared or unique. For non-owning parameters, raw pointers or (const) references are the current recommendation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM