为什么在分配给成员变量之前获取unique_ptr的返回是一个问题?
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()
返回按值,那么它返回的是一个临时的,它将在完整表达式后立即被销毁。然后,person
从临时获得的原始指针也被销毁(由拥有它的临时std::unique_ptr<Person>
销毁(,以后对它的任何取消引用都会导致 UB。
在第一个代码段中,您使用命名变量来存储返回的std::unique_ptr<Person>
,它不会被销毁,直到超出声明的范围,然后
相关文章:
- 我不断收到 [错误] ID 返回 1 退出状态错误,但看不到问题所在
- 从 C++ 中的函数返回数组地址问题
- 在类中返回结构时出现问题
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 这个返回元素位置的基于循环的函数有什么问题?
- 编译问题:在函数"_start"中:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 特征返回类型的 pybind11 问题
- 类的大问题,以及从空函数c++返回
- 基本的 c++ 问题:如果我在函数中创建某些内容并返回它会发生什么?
- C++模板编程设计问题 - 根据输入文件返回不同的类型
- 存储另一个函数返回的布尔数组时遇到问题
- 为什么在分配给成员变量之前获取unique_ptr的返回是一个问题?
- 从 C++ 中的函数返回双精度的问题
- 返回不停止函数,递归函数问题?(编程练习,动态规划,Levenshtein 回溯)
- 字符 * 未从重载运算符或内存管理问题正确返回
- 带有指针返回问题的c++协方差问题
- 在 c++ 中使用 sqlite 的 void 函数中的"返回"问题
- C++动态矩阵乘法返回问题
- C++ 无限循环,返回问题
- STL 列表<mystruct>返回问题