Rapidjson: Document 放到另一个Document下面,为什么会core_dump?

Created on 12 Jul 2020  ·  3Comments  ·  Source: Tencent/rapidjson

root@NB80261026:/mnt/d/workspace/cpp/test_rapidjson# cat main.cc 
#include <string>
#include <iostream>
#include <rapidjson/document.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/prettywriter.h>
#include <unistd.h>

std::string Dom2String(rapidjson::Document &d)
{
     rapidjson::StringBuffer buffer;
     rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
     d.Accept(writer);
     return buffer.GetString();
}

void function(rapidjson::Document &a)
{
    rapidjson::Document b1(rapidjson::kObjectType);
    b1.AddMember("a", rapidjson::Value(1).Move(), b1.GetAllocator());
    a.AddMember("test1", b1, a.GetAllocator());
    std::cout << "in function:" << std::endl;
    std::cout << Dom2String(a) << std::endl;
    return ;
}

int main()
{
    rapidjson::Document a(rapidjson::kObjectType);
    function(a);
    usleep(1000 * 1000);
    std::cout << "out function:" << std::endl;
    std::cout << Dom2String(a) << std::endl;
    return 0;
}
root@NB80261026:/mnt/d/workspace/cpp/test_rapidjson# g++ main.cc -I /mnt/d/software/rapidjson-master/include -g -O0
root@NB80261026:/mnt/d/workspace/cpp/test_rapidjson# ./a.out 
in function:
{"test1":{"a":1}}
out function:
Segmentation fault (core dumped)
root@NB80261026:/mnt/d/workspace/cpp/test_rapidjson# 
question

Most helpful comment

b1 的内存还是来自于 b1 的分配器。
需要先用 a 的分配器来复制 b1。

~cpp
a.AddMember("test1", Value(b1, a.GetAllocator()).Move(), a.GetAllocator());
~

All 3 comments

在function函数中,虽然b1是局部变量,
但是当我调用a.AddMember("test1", b1, a.GetAllocator());之后,
b1的内存就应该通过Move语义,转移给a来管理了吧,
这样退出function函数之后,虽然b1析构了,但是他的析构应该是平凡的啊,
这样操作a的时候,不应该出现core dump才对啊,

很疑惑。

b1 的内存还是来自于 b1 的分配器。
需要先用 a 的分配器来复制 b1。

~cpp
a.AddMember("test1", Value(b1, a.GetAllocator()).Move(), a.GetAllocator());
~

tks

Was this page helpful?
0 / 5 - 0 ratings

Related issues

srikarad07 picture srikarad07  ·  5Comments

OlafvdSpek picture OlafvdSpek  ·  6Comments

dan-ryan picture dan-ryan  ·  6Comments

lelit picture lelit  ·  5Comments

accelerated picture accelerated  ·  6Comments