英文:
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<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.
答案1
得分: 6
std::shared_ptr<Derived>
隐式可转换为 std::shared_ptr<Base>
。当这种情况发生时,会创建一个新的临时对象,可以绑定到 std::shared_ptr<Base>&&
。由于该对象是一个 prvalue,其生命周期会延长到引用的生命周期。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论