4

I'm passing pointer to rapidjson::Document as an argument.

foo(rapidjson::Document* jsonDocument)
{
    std::cout << jsonDocument["name"] << std::endl;
}

But I cannot do jsonDocument["name"] to access the name attribute.

Attempting to not use pointers leads to an error:

error: 'rapidjson::GenericDocument<Encoding, Allocator, StackAllocator>::GenericDocument(const rapidjson::GenericDocument<Encoding, Allocator, StackAllocator>&) [with Encoding = rapidjson::UTF8<>; Allocator = rapidjson::MemoryPoolAllocator<>; StackAllocator = rapidjson::CrtAllocator]' is private
GenericDocument(const GenericDocument&);

Can someone help me?

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
J. Doe
  • 97
  • 2
  • 6
  • 2
    Can't find the dupe, but there are many. In short you need to dereference the pointer before using it like `(*jsonDocument)["name"]` or `jsonDocument[0]["name"]` or use a reference such as `rapidjson::Document& jsonDocument`. – nwp Feb 13 '17 at 15:46
  • Using a reference is the best solution. – Martin Bonner supports Monica Feb 13 '17 at 16:11

1 Answers1

5

Use a reference or a value as argument. Using the [] with a pointer will try to use your document as if it was an array of document. A reference or a value will call the expected operator.

// a const reference
foo(const rapidjson::Document& jsonDocument) {
    std::cout << jsonDocument["name"] << std::endl;
}

// a copy (or move)
foo(rapidjson::Document jsonDocument) {
    std::cout << jsonDocument["name"] << std::endl;
}

I'd recommend you to use the reference, as your function don't need to consume any resources in the document, but only observe and print a value.

The call of this function will look like this:

rapidjson::Document doc = /* ... */;

foo(doc);
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
  • Thank you, I'm using a const reference. – J. Doe Feb 13 '17 at 16:33
  • Could you add how you can save a Value in a local variable if you pass the Document as const reference? Here an example `foo(const rapidjson::Document &d){ const Value &v = d["name"]; }` – krjw Dec 06 '18 at 14:28
  • @i7clock do you mean a copy? If yes, then `auto doc_copy = doc!` should be sufficient. – Guillaume Racicot Dec 06 '18 at 15:26
  • I mean for further extracting values and manipulating the DOM, but thanks for showing me how to do a copy – krjw Dec 06 '18 at 18:04