【发布时间】:2020-01-07 23:10:35
【问题描述】:
问题已更新!
我有一个 std::string 对象,std::thread 应该将它复制到它的内部存储中,为什么下面的代码仍然不起作用?(已修复)
如果我分离 t(f, 5, std::string(buf)),则根本没有输出! (已修复)
#include <thread>
#include <iostream>
#include <unistd.h>
using namespace std;
void f(int i, const std::string &str) {
printf("i = %d, str = %s\n", i, str.c_str());
}
void oops(int ival) {
char *buf = new char[32]{0};
snprintf(buf, 32, "%i", ival);
// maybe danling pointer, if it's a danling pointer, the content of buf is undefined
// in this program it happens to be 1999.
std::thread t(f, 3, buf);
t.detach();
delete [] buf;
}
void not_oops(int ival) {
char *buf = new char[32]{0};
snprintf(buf, 32, "%i", ival);
std::thread t(f, 5, std::string(buf));
t.detach();
delete [] buf;
}
int main() {
oops(1992); // This is buggy
not_oops(1999);
}
预期输出:
i = 3, str = 1992
i = 5, str = 1999
实际输出:
i = 3, str = 1999
i = 5, str = 1999
【问题讨论】:
-
您需要在
main中添加一些延迟以等待结果(也许通过使用this_thread::sleep_for()?)。两次调用detach,main立即结束。您的not_oops功能正常工作,当您修复延迟问题时,您将看到正确的结果。 -
是的,在
oops它正在复制值。该值只是一个指针。 -
但是输出还是不对...
标签: c++11 g++ ubuntu-18.04 clang++ stdthread