Search code examples
c++constructorpass-by-referencemovepass-by-value

Should shared_ptr constructor arguments be passed by value


When I pass a shared_ptr to a constructor that copies that argument into a member shared_ptr, should this parameter be passed by value?

Example:

struct MyClass {
    MyClass(std::shared_ptr<MyDependency> dep) 
        : dep(dep)
    {}

    std::shared_ptr<MyDependency> dep;
};

If constructed with a temporary (MyClass(std::make_shared<...>())) the compiler should move the argument (once or twice?).

Is the compiler able to "auto" move dep to dep, or should I use : dep(std::move(dep))?

If constructed with a lvalue the value will be copied (min. one times).

On the other hand, passing the shared_ptr by const-ref will always copy the pointer.

So should constructor arguments be passed by value if they will be directly copied into a member?

Edit: The parameter/member must be a shared_ptr.


Solution

  • Should shared_ptr constructor arguments be passed by value

    If you intend to share ownershi i.e. you want to keep a copy: Yes, passing by value is the preferred way.

    If constructed with a temporary ... the compiler should move the argument (once or twice?).

    First the argument is move constructed, then the member is initialized (see below). The construction of the argument may be elided in some cases.

    should I use : dep(std::move(dep))

    Yes, you should. The argument has a name, and so it is an lvalue. To move construct the member, you need to have an rvalue.