Protocol Buffers 是否支持移动构造函数
Does Protocol Buffers support move constructor
我已经检查了 move constructor spec and a Message constructor 来源,但没有找到。
如果没有,有人知道添加它的计划吗?
我正在使用 proto3
语法,编写一个库并考虑 return 到值与 unique_ptr。
从 2.6.1 版开始,C++ protobuf 编译器仅生成复制构造函数和复制赋值运算符。但是如果你的编译器支持return value optimization(并且满足它的条件)复制构造函数无论如何都不会被调用。
您可以将一些打印语句添加到消息的复制构造函数的生成代码中,以查看它们是否真的被调用。您也可以通过编写一个 protoc 插件来做到这一点,因此它在 protoc 调用之间持续存在。
如果您尝试使用赋值运算符,RVO 将进行优化以防止额外复制。
// RVO will bring the return value to a without using copy constructor.
SomeMessage a = SomeFooWithMessageReturned();
如果你想用std::move
将一个左值移动到list/sub消息等,尝试使用ConcreteMessage::Swap
方法。换的东西就没用了
// Non-copy usage.
somemessage.add_somerepeated_message()->Swap(&a);
somemessage.mutable_somesinglar_message()->Swap(&a);
// With message copying
somemessage.add_somerepeated_message()->CopyFrom(a);
*somemessage.mutable_somesinglar_message() = a;
根据 https://github.com/google/protobuf/issues/2791 这将在 Protobuf 版本 3.4.0 中得到支持。
我已经检查了 move constructor spec and a Message constructor 来源,但没有找到。
如果没有,有人知道添加它的计划吗?
我正在使用 proto3
语法,编写一个库并考虑 return 到值与 unique_ptr。
从 2.6.1 版开始,C++ protobuf 编译器仅生成复制构造函数和复制赋值运算符。但是如果你的编译器支持return value optimization(并且满足它的条件)复制构造函数无论如何都不会被调用。
您可以将一些打印语句添加到消息的复制构造函数的生成代码中,以查看它们是否真的被调用。您也可以通过编写一个 protoc 插件来做到这一点,因此它在 protoc 调用之间持续存在。
如果您尝试使用赋值运算符,RVO 将进行优化以防止额外复制。
// RVO will bring the return value to a without using copy constructor. SomeMessage a = SomeFooWithMessageReturned();
如果你想用
std::move
将一个左值移动到list/sub消息等,尝试使用ConcreteMessage::Swap
方法。换的东西就没用了// Non-copy usage. somemessage.add_somerepeated_message()->Swap(&a); somemessage.mutable_somesinglar_message()->Swap(&a); // With message copying somemessage.add_somerepeated_message()->CopyFrom(a); *somemessage.mutable_somesinglar_message() = a;
根据 https://github.com/google/protobuf/issues/2791 这将在 Protobuf 版本 3.4.0 中得到支持。