Using the assignment operator in C++

2,093 views
Skip to first unread message

JonnyDee

unread,
Jul 21, 2011, 8:02:34 PM7/21/11
to Protocol Buffers
Hello,

I've assumed the API allows to use the assignment operator to copy the
content of on message to another one like this:

MyMessage msg1, msg2;
msg1.set_name("Foo Bar");
msg2 = msg1;

My assumption was the using the API like this would be intuitively
enough to let the generated class files support it.
But as I am currently struggling with strange behaviors of my code I
took the time to analyze the protobuf API in more detail, but I could
not find any operator overloading, which delegates the assigment
operation to a call equivalent to msg2.CopyFrom(msg1). Also, examples
I could find only use those explicit method calls. So now I'm not sure
if I am using the API wrongly or not. Would you mind to let me know if
using assignment instead of 'CopyFrom' method is safe or not? I would
have to change a lot of code if I needed to call that method in order
to be safe. So I just would like to know if this effort is worth it.

Best regards,
Jonny

Jason Hsueh

unread,
Jul 22, 2011, 2:04:18 PM7/22/11
to JonnyDee, Protocol Buffers
The assignment operator simply wraps CopyFrom, so the behavior is exactly the same. Stylistically we prefer to use CopyFrom over =, because it can be an expensive operation and = makes it look deceptively simple. The operator= overload primarily exists for compatibility with STL, but of course you're free to use it as you choose.


--
You received this message because you are subscribed to the Google Groups "Protocol Buffers" group.
To post to this group, send email to prot...@googlegroups.com.
To unsubscribe from this group, send email to protobuf+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/protobuf?hl=en.


JonnyDee

unread,
Jul 22, 2011, 7:47:15 PM7/22/11
to Protocol Buffers
Thank you very much for your fast response :)

Best regards,
Jonny

On Jul 22, 8:04 pm, Jason Hsueh <jas...@google.com> wrote:
> The assignment operator simply wraps CopyFrom, so the behavior is exactly
> the same. Stylistically we prefer to use CopyFrom over =, because it can be
> an expensive operation and = makes it look deceptively simple. The operator=
> overload primarily exists for compatibility with STL, but of course you're
> free to use it as you choose.
>
Reply all
Reply to author
Forward
0 new messages