阅读Similar Question中的答案后,我仍然想知道为什么这个代码片段没有出现段错误。临时对象“data”应在离开作用域后释放。但显然,“数据”并未公布。 有人可以帮助我吗? 谢谢
#include <iostream>
#include <string>
#include <thread>
using namespace std;
void thfunc(string &data)
{
for (;;)
{
cout << data << endl;
}
}
int main()
{
{
string data = "123";
std::thread th1(thfunc, std::ref(data));
th1.detach();
}
for (;;)
{
cout << "main loop" << endl;
}
return 0;
}
最佳答案
临时对象是按照标准释放的,导致未定义的行为。实现可以做任何事情,包括将对象的字节保留在堆栈内存中直到它们被覆盖,这允许您的代码(错误地)工作。
当我反汇编编译器(clang++ 9.0.1)生成的二进制文件时,我注意到当包含 data
的 block 时,堆栈指针没有“回归”。结束,从而防止它被覆盖
cout << "main loop" << endl;
导致函数调用。
此外,由于 short string optimization ,实际的 ASCII“123”存储在 std::string
中对象本身而不是在堆分配的缓冲区中。
draft standard说如下:
6.6.4.3 Automatic storage duration
Block-scope variables not explicitly declared static, thread_local, or extern have automatic storage duration. The storage for these entities lasts until the block in which they are created exits.
在实验中,如果我使字符串足够长以禁用短字符串优化,程序仍然会默默地工作,因为缓冲区中的字节在我的实验中恰好保持不变。如果我启用 ASAN,我会收到正确的堆释放后使用警告,因为这些字节是在字符串生命周期结束时释放的,但却是通过非法使用指向现已破坏的字符串的指针来访问的。
关于c++ - C++11 的线程安全性以及通过临时对象的引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61399544/