我正在使用C ++的nlohmann :: json库。我有以下代码。
#include <iostream>
#include <json.hpp>
using json = nlohmann::json;
int main(){
json m;
m["aaaaaaaa"] = 0;
m["bbbbbbbbbbbbb"] = 0;
m["ccccccccccccccccccc"] = 0;
m["dddddddddddddddddd"] = 0;
m["eeeeeeeeeeeeeeeeee"] = 0;
m["fffffffffffff"] = 0;
m["gggggggggggg"] = 0;
m["hhhhhhhhhhhh"] = 0;
m["iiii"] = 0;
m["jjjjjjjjjjjjjjj"] = 0;
m["kkkkkkkkkkkkkk"] = 0;
m["llllllllllllllll"] = 0;
for (int i = 0; i < 100; i++) {
const char* mstr = m.dump().c_str();
std::cout << strlen(mstr) << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
我希望strlen(mstr)for循环的所有100次迭代的输出都完全相同。
在某些运行中,我得到了预期的输出。 …
考虑下面的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;
}
Run Code Online (Sandbox Code Playgroud)
调用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()); …Run Code Online (Sandbox Code Playgroud)