First, the code...
#include <rapidjson/document.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
#include <iostream>
int main(int argc, char* argv[]) {
using namespace rapidjson;
Value author;
{
Document document;
char buffer[10];
int len = sprintf(buffer, "%s %s", "Milo", "Yip"); // dynamically created string.
author.SetString(buffer, len, document.GetAllocator());
}
// Checkpoint 1
StringBuffer buffer;
Writer<rapidjson::StringBuffer> writer( buffer );
// Accesses invalidated memory in author
author.Accept( writer );
std::cout << buffer.GetString( ) << std::endl;
return 0;
}
This code is a little contrived, and is a small variation on one of the examples from the docs. If I understand RapidJson correctly, the string inside author has been allocated using the allocator from document, and is owned by document. Consequently, when document drops out of scope, just before 'Checkpoint 1', author is invalidated.
I want be wrong about this, because if it's true it makes it more or less impossible to regard Value objects as first class objects, because they have a hidden dependency on their allocators, and to build Value objects piecemeal. Either you have to pass in an allocator to every function which builds a Value, or have one or more global allocators sitting around which you ensure remain in scope.