为什么在分配给成员变量之前获取unique_ptr的返回是一个问题?

Why is it a problem to get the return of unique_ptr before assigning to a member variable?

本文关键字:返回 问题 一个 ptr 成员 分配 变量 unique 获取 为什么      更新时间:2023-10-16

为什么结果不同,第二种方法出现问题?

1(没有错误。

auto person = getPerson(); // return type : std::unique_ptr<Person>
static_cast<Student*>(person.get())->foo(); // Student inherits Person

2( 进入函数 foo(( 前的分割错误

auto person = getPerson().get();
static_cast<Student*>(person)->foo(); 

我想getPerson()返回按值,那么它返回的是一个临时的,它将在完整表达式后立即被销毁。然后,person从临时获得的原始指针也被销毁(由拥有它的临时std::unique_ptr<Person>销毁(,以后对它的任何取消引用都会导致 UB。

在第一个代码段中,您使用命名变量来存储返回的std::unique_ptr<Person>,它不会被销毁,直到超出声明的范围,然后

就可以了。