Poperton
Poperton

Reputation: 2127

No way to set protobuf element by copyin instead of set_allocated_something?

On my generated protobuf classes, I see only set_allocated_something.

Example:

syntax = "proto3";
import "uuid.proto";
import "openvpn.proto";
package message;

message VPN {
    UUID uuid = 1;
    oneof vpn {
        OpenVPN openVPN = 2;
    }
}

then I have:

OpenVPN openVPN;
//fill openVPN
auto vpnAny = someObject.add_vpns();
vpnAny->set_allocated_openvpn(&openVPN);

The following code crashes because I'm adding an object for which I own the data, and then set_allocated_openvpn is going to delete it first, then the scope is going to delete it a second time.

The alternative would be to do

OpenVPN* openVPN = new OpenVPN();

but I want to avoid raw pointers + new.

Why simply won't protobuf generate a method that copies the data? Why I can only pass allocated data pointer? And how should I deal with this situation?

Upvotes: 0

Views: 439

Answers (1)

Rafael Lerm
Rafael Lerm

Reputation: 1400

Protobuf generates copy constructors and copy assignment operators for every type. So the most normal way to copy a message into another would be something like

OpenVPN openVPN;
// (...)
*someObject.add_vpns() = openVPN;

Upvotes: 1

Related Questions