eikos quinn
eikos quinn

Reputation: 13

Destructor getting called on protobuf object

I've implemented two simple protobuf messages

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

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

I then have two wrapper classes of the protobuf objects. Inside the Object2Wrapper, after I call ToProtobuf when it returns the destructor is called on obj1 for some reason I cannot understand.

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
        }
};

Upvotes: 1

Views: 1110

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122830

The reason is that you pass the object obj1 by value. A copy of the parameter is created and this copy is destroyed when the function returns.\

I guess what you really wanted to do is to pass the object by reference. I.e.

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

Only when you pass-by-reference, you can alter the object inside the function. As you have it now, any changes to obj1 inside the function have zero effect on the parameter that is passed to the function.

Upvotes: 2

Related Questions