为什么在赋值给成员变量之前,获取unique_ptr的return是个问题?

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

为什么结果不一样,问题出现在第二种方法中?

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() returns是按值的,那么returns是个临时的,满表达式后马上销毁。然后从临时文件中获得的原始指针 person 也被销毁了(由拥有它的临时文件 std::unique_ptr<Person> ),之后对它的任何取消引用都会导致 UB。

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