c++jsonrapidjson

Why is the assignment operator private in some libraries? (e.g. RapidJson)


I have encountered some libraries like rapidjson (or wjwwood/serial) where the assignment operator of their more important object is private. When I try to use the operator on rapidJson:

    test.Parse(jsonScheme);
    rapidjson::Document test2;
    test2 = test;

... and it produces the following error ...

[build] ../main.cpp:45:10: error: ‘rapidjson::GenericDocument<Encoding, Allocator, StackAllocator>& rapidjson::GenericDocument<Encoding, Allocator, StackAllocator>::operator=(const rapidjson::GenericDocument<Encoding, Allocator, StackAllocator>&) [with Encoding = rapidjson::UTF8<>; Allocator = rapidjson::MemoryPoolAllocator<rapidjson::CrtAllocator>; StackAllocator = rapidjson::CrtAllocator]’ is private within this context
[build]    45 |  test2 = test;
[build] In file included from ../main.cpp:7:
[build] .././includes/rapidjson/document.h:2850:22: note: declared private here
[build]  2850 |     GenericDocument& operator=(const GenericDocument&);

I see in rapidjson docs that they use the assignment operator with no problem. What am I doing wrong?


Solution

  • rapidjson is compatible with pre C++11 compiler, where the =delete directive is not available.

    So as @Jarod42 pointed , declaring Copy constructor or copy assignment operator is the old way of prohibiting usage of them. By the way this is stated in some comments,

    For example in reader.h :

    private:
    // Prohibit copy constructor & assignment operator.
    GenericReader(const GenericReader&);
    GenericReader& operator=(const GenericReader&);
    

    Generally, in C++ if the copy operation is not available usually it means that this is an extensive , state full object (in term of resource usage), that would not make sense to copy.

    At least on version v1.1 (last "official" release), most of these classes does not have move constructor neither. It means that you have to manage them through pointers (smart pointers preferably) if you want to store them in container.

    Last point, as you have figured out, nlohmann json API is more "friendly" and intuitive, no comparison. Some features of rapidjson are not available in it nevertheless.