首页 > 解决方案 > 为什么赋值运算符在某些库中是私有的?(例如 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 文档中看到他们使用赋值运算符没有问题。我究竟做错了什么?

标签: c++jsonrapidjson

解决方案


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 的某些功能在其中不可用。


推荐阅读