use*_*399 1 c++ string json pointers nlohmann-json
我正在使用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次迭代的输出都完全相同。
在某些运行中,我得到了预期的输出。
223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223程序以退出代码结束:0
但是在其他运行中,我偶尔会看到字符串的长度为0。
223 0 223 223 223 223 223 223 223 223 223 0 223 223 223 223 223 0 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 0 223 223 223 223 223 223 223 223 0 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223 223程序以退出代码结束:0
这怎么可能发生?
dump函数将一个对象返回到堆栈。通过使用该对象的指针,您有时可能会发现对象内存已被重用,然后才可以打印该值。应该做的是直接存储转储的字符串:
std::string mstr = m.dump();
std::cout << mstr.size() << std::endl;
Run Code Online (Sandbox Code Playgroud)