【问题标题】:c++ passing json object by referencec ++通过引用传递json对象
【发布时间】:2022-02-01 08:14:03
【问题描述】:

在下面的代码中,我接收来自客户端的请求,将它们放在我的服务器类上的一个 json 对象上并将其发送到推送器(直接连接到网站,将我的数据放在那里以便我可以搜索数据容易地) 代码工作得很好,但是我的经理说我需要在这段代码中通过引用传递 json,我不知道该怎么做。 在服务器类上:

grpc::Status RouteGuideImpl::PubEvent(grpc::ServerContext *context, 
                    const events::PubEventRequest *request, 
                    events::PubEventResponse *response){
    for(int i=0; i<request->event_size();i++){
    nhollman::json object;
    auto message = request->events(i);
    object["uuid"]=message.uuid();
    object["topic"]=message.type();
    pusher.jsonCollector(obj);
    }
    ...
}

关于 Pusher 类:

private:
    nholmann::json queue = nlohmann::json::array();
public:
    void Pusher::jsonCollector(nlohmann::json dump){
        queue.push_back(dump);
    }
    void Pusher::curlPusher(){
        std::string str = queue.dump();
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, str.data());
...
}

据我所知,我需要通过引用发送 json 对象。我该怎么做?

【问题讨论】:

  • 通过引用传递参数是每个 C++ 程序员都应该知道的基本知识之一。获取some good C++ books 并重新学习基础知识。
  • 我习惯了 java 和 python,所以我对指针和数组的整个概念都是指针等感到有点痛苦。
  • 在 C++ 中,数组可以衰减指向指针(指向数组的第一个元素),但数组本身不是指针。如果您的任务是使用 C++ 编程,您的公司应该为您提供学习它的资源。就像我之前链接的一些书一样。

标签: c++ json grpc pass-by-reference


【解决方案1】:

简单的答案是改变

void Pusher::jsonCollector(nlohmann::json dump)

到

void Pusher::jsonCollector(const nlohmann::json& dump)

(请注意,如果这是在类中,那么 Pusher:: 是一个非标准的 Visual Studio 扩展)。

这将减少对象从 2 复制到 1 的次数,但是您可以使用 std::move 完全避免复制:

void Pusher::jsonCollector(nlohmann::json dump){
        queue.push_back(std::move(dump));
    }

然后调用它:

pusher.jsonCollector(std::move(obj));

如果您想强制执行此行为以确保jsonCollector 的调用者始终使用std::move,您可以将jsonCollector 更改为:

void Pusher::jsonCollector(nlohmann::json&& dump){
        queue.push_back(std::move(dump));
    }

【讨论】:

    【解决方案2】:

    嗯,引用是区分 C 和 C++ 的众多特性之一。

    在其他语言中,比如 python 或 java,当你将一个对象(不是基本类型)传递给一个函数并在那里改变它时,它也会在调用者实体中改变。在这些语言中,您没有指针,但您需要传递对象,而不是副本。

    这就是 C++ 中的引用。它们像值类型一样使用,但它们不是副本。 指针可以是nullptr(或C 中的NULL),引用不能。指针指向的地址可以更改(分配),您不能更改引用所指的对象。

    查看https://en.cppreference.com/w/cpp/language/reference 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2011-07-06
      • 2013-08-11
      • 2017-09-11
      • 2016-10-11
      • 2012-07-07
      相关资源
      最近更新 更多