Shall I put protobuf message in unique_ptr to avoid copy?

29 views
Skip to first unread message

river

unread,
Sep 9, 2020, 6:48:37 AM9/9/20
to Protocol Buffers
here is my code, should I directly usage vector<IndexVector> ?
    std::vector<std::unique_ptr<IndexVector>> ret; // IndexVector is a protobuf message type, sizeof ... = 72

    while (result.next()) {
        std::unique_ptr<IndexVector> indexVector {std::make_unique<IndexVector>()};
        int64_t poiId = result.getLLong(1);
        int64_t pictureId = result.getLLong(2);
        bool isDel = result.getInt(3) != 0;

        indexVector->set_id(pictureId);
        indexVector->set_poiid(poiId);
        indexVector->set_isdel(isDel);

        ret.push_back(indexVector);
    }
    return ret;

Adam Cozzette

unread,
Sep 9, 2020, 11:38:07 AM9/9/20
to river, Protocol Buffers
That sounds like a reasonable way to do it. Another thing you could do is that if you know how big the vector will be, you can call indexVector.reserve() to reserve the correct size, then add each element with indexVector.emplace_back() and initialize its fields in place. That would let you use std::vector<IndexVector> without any extra copying.

--
You received this message because you are subscribed to the Google Groups "Protocol Buffers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to protobuf+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/protobuf/ba2870b6-c2ac-4d3c-89b6-4ea8f2cfcba4n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages