在 protobuf 对象上调用析构函数

Destructor getting called on protobuf object

我实现了两个简单的 protobuf 消息

package TestNamespace;
message Object1 {
  int32 age = 1;
  int32 speed = 2;
}

message Object2 {
  Object1 obj = 1;
  int32 page_number = 2;
}

然后我有两个 protobuf 对象的包装器 类。 在 Object2Wrapper 内部,在我调用 ToProtobuf 之后 returns 由于某种我无法理解的原因在 obj1 上调用了析构函数。

class Object1Wrapper
    {
    public:
        int32_t Age{};
        int32_t Speed{};

        void ToProtobuf(TestNamespace::Object1 obj1)
        {
            obj1.set_age(Age);
            obj1.set_speed(Speed);
            //After this line the ~destructor is called on obj1
        }
};

class Object2Wrapper{

    public:
        Object1Wrapper obj1{};
        int32_t page_number{};

        void ToProtobuf(TestNamespace::Object2 obj2Param)
        {
            TestNamespace::Object1 * obj1Proto = obj2Param.mutable_obj();
            obj1::ToProtobuf(*obj1Proto);
            // Do stuff.... but obj1Proto is empty
        }
};

原因是你按值传递了对象obj1。创建参数的副本,并在函数 returns.\

时销毁此副本

我猜你真正想做的是通过引用传递对象。 IE。

void ToProtobuf(TestNamespace::Object1& obj1)
    {
        obj1.set_age(Age);
        obj1.set_speed(Speed);
        //After this line the ~destructor is called on obj1
    }

只有当你通过引用传递时,你才能改变函数内部的对象。正如您现在所做的那样,函数内部对 obj1 的任何更改对传递给函数的参数的影响为零。