此代码可以吗?我知道函数返回后,参考计数器将降为零,因此应释放内存。但是它可以工作,并且可以在函数外部成功打印出取消引用。
有人可以解释我想做的事是对还是错,为什么?谢谢
#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:\或使您的狗怀孕。