繁体   English   中英

将指向临时 std::string 的指针传递给另一个线程

[英]Passing pointer to a temporary std::string to another thread

考虑以下 C++ 程序

#include <iostream>
#include <thread>
#include <string>

std::string getString() {
    return "hello world";
}

void printString(const char* s)
{
    std::cout << s << std::endl;
}

int main()
{       
    std::thread T(printString, getString().c_str());

    T.join();

    return 0;

}

getString()的调用将返回一个临时std::string并且值getString().c_str()是一个指向临时堆栈变量的指针。

由于每个线程都有自己的堆栈(但共享堆),因此将指向主线程上的字符串的指针传递给某个线程T在理论上不应该工作对吧?

为什么此代码编译并运行以打印hello world 还是我遇到了某种未定义的行为?

编辑:

如果程序看起来像这样(没有线程)怎么办

#include <iostream>
#include <thread>
#include <string>

std::string getString() {
    return "hello world";
}

void printString(const char* s)
{
    std::cout << s << std::endl;
}

int main()
{       
    printString(getString().c_str());                
    return 0;

}

还是我遇到了某种未定义的行为?

这正是发生的事情。 getString返回的字符串只存在到 epxresion 结束

std::thread T(printString, getString().c_str());

这意味着在printString中,您有一个指向不再有效的数据的指针。 您可能会得到其中包含的内容,或者可能会发生其他事情。 访问指针是未定义的行为,因此您得到的任何结果都是“正确的”。


如果您将getString更改为

const char * getString() {
    return "hello world";
}

并创建线程

std::thread T(printString, getString());

那么这没关系,因为"hello world"具有 static 存储持续时间,因此它将在程序生命周期的 rest 中存在

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM