How do I pass smart pointers into functions?

后端 未结 3 1667

When passing objects into functions, do the same rules apply to smart pointers as to other objects that contain dynamic memory?

When I pass, for example, a std::

3条回答
  •  逝去的感伤
    2021-01-30 19:04

    A smart pointer is an object that refer to another object an manages its lifetime.

    Passing a smart pointer reuquires to respect the semantics the smart poitner support:

    • Passing as const smartptr& always work (and you cannot change the pointer, but can change the state of what it points to).
    • Passing as smartptr& always work (and you can change the pointer as well).
    • Passing as smartptr (by copy) works only if smartptr is copyable. It works with std::shared_ptr, but not with std::unique_ptr, unless you "move" it on call, like in func(atd::move(myptr)), thus nullifying myptr, moving the pointer to the passed parameter. (Note that move is implicit if myptr is temporary).
    • Passing as smartptr&& (by move) imposes the pointer to be moved on call, by forcing you to explicitly use std::move (but requires "move" to make sense for the particular pointer).

提交回复
热议问题