Search code examples
c++shared-ptrrvalue-reference

Why can I bind base class shared_ptr rvalue reference to derived class shared_ptr?


so I know we cannot bind rvalue reference to an lvalue, so the following code won't compile:

class Base {};

int main(int argc, char** argv) {
    std::shared_ptr<Base> base = std::make_shared<Base>();
    std::shared_ptr<Base>&& ref = base;
}

but the next code can compile, and I can't figure out why.

class Base {};
class Derived : public Base {};

int main(int argc, char** argv) {
    std::shared_ptr<Derived> derived = std::make_shared<Derived>();
    std::shared_ptr<Base>&& ref = derived;
}

With type deduction, auto&& and T&& are forward reference, because they can be lvaue reference, const reference or rvalue reference. But here is no type deduction in my case(or what I think), maybe in share_ptr, but I'm referencing share_ptr itself, not its underlying object, so I'm stuck.


Solution

  • std::shared_ptr<Derived> is implicitly convertible to std::shared_ptr<Base>. When that happens, a new, temporary object is created, which a std::shared_ptr<Base>&& can bind to. Since that object is a prvalue, its lifetime gets extended to the lifetime of the reference.