为什么我可以将基类的shared_ptr右值引用绑定到派生类的shared_ptr?

huangapple go评论65阅读模式
英文:

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

问题

我知道我们不能将右值引用绑定到左值,所以下面的代码不会编译:

class Base {};

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

但是下面的代码可以编译,我搞不清楚为什么。

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;
}

使用类型推断,auto&&T&& 都是“正向引用(forward reference)”,因为它们可以是左值引用、常量引用或右值引用。但在我的情况下(或者我认为的情况下),没有类型推断,也许在 shared_ptr 中有,但我引用的是 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&lt;Base&gt; base = std::make_shared&lt;Base&gt;();
    std::shared_ptr&lt;Base&gt;&amp;&amp; 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&lt;Derived&gt; derived = std::make_shared&lt;Derived&gt;();
    std::shared_ptr&lt;Base&gt;&amp;&amp; ref = derived;
}

With type deduction, auto&amp;&amp; and T&amp;&amp; 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.

答案1

得分: 6

std::shared_ptr<Derived> 隐式可转换为 std::shared_ptr<Base>。当这种情况发生时,会创建一个新的临时对象,可以绑定到 std::shared_ptr<Base>&&。由于该对象是一个 prvalue,其生命周期会延长到引用的生命周期。

英文:

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

huangapple
  • 本文由 发表于 2023年3月1日 12:18:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75599534.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定