c++ - 在函数返回中返回新分配的 shared_ptr 的引用是否合法?

标签 c++ c++11

这段代码可以吗?我知道函数返回后引用计数器会降为零,因此应该释放内存。但它可以工作并在函数外成功打印取消引用。

有人可以解释一下我正在尝试做的事情是否错误,为什么? 谢谢

#include <iostream>
#include <memory>
#include <string>

std::string& get_string(bool en)
{ 
  return *std::make_shared<std::string>("hello world");
}

int main () {
  auto& my_str = get_string(true);
  std::cout << "str=" << my_str <<std::endl;
  return 0;
}

输出:

> ./main
str=hello world

最佳答案

一旦您从 get_string 返回,您的临时共享指针将被销毁,其中的 std::string 也将被销毁。因此,您使用的是悬空引用,它会调用未定义的行为。

详细解答here .

由于未定义的行为,程序可能按预期执行,但它也可以做任何它想做的事。

关于c++ - 在函数返回中返回新分配的 shared_ptr 的引用是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58607070/

相关文章:

c++ - 如何修复给出 'declaration has no storage class or type specifier' 错误的派生类?

c++ - ADO 命令说我正在插入 NULL,而我不是

c++ - 如何强制编译器显示隐式构造函数

c++ - 使用 C++ 元编程构建静态字符串

c++ - 代码在 Sun Studio 上编译但在 gcc 上出错

c++ - Eigen::aligned_allocator 因 std::unordered_multimap 而失败

c++ - 让 GDB 显示模板参数的类型

c++ - 检测媒体基础中的音量或静音

c++ - Sqlite3,我不明白为什么我的指针返回为空

C++ DLL 不导出函数