为什么赋值运算符在某些库中是私有的? (例如 RapidJson)

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

我遇到过一些像 rapidjson(或 wjwwood/serial)这样的库,其中更重要的对象的赋值运算符是私有的。 当我尝试在 rapidJson 上使用运算符时:

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

... 并产生以下错误...

[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&);

我在 rapidjson 文档中看到他们使用赋值运算符没有问题。我做错了什么?

rapidjson 与 C++11 之前的编译器兼容,其中 =delete 指令不可用。

正如@Jarod42 指出的那样,声明复制构造函数或复制赋值运算符是禁止使用它们的旧方法。顺便说一下,这在一些评论中有说明,

例如reader.h:

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

通常,在 C++ 中,如果复制操作不可用,通常意味着这是一个扩展的、状态完整的对象(就资源使用而言),复制没有意义。

至少在 v1.1 版本(最后一个“官方”版本)上,这些 类 中的大部分都没有移动构造函数。 这意味着如果你想将它们存储在容器中,你必须通过指针(最好是智能指针)来管理它们。

最后一点,如您所见,nlohmann json API 更“友好”和直观,没有可比性。尽管如此,rapidjson 的某些功能在其中不可用。