[C++] Support C++ object copies and moves (#5988)

Augment the C++ generator to emit a C++ copy constructor and a by-value
copy assignment operator. This is enabled by default when the C++
standard is C++11 or later. These additional functions are only emitted
for objects that need it, typically tables containing other tables.

These new functions are declared in the object table type and are
defined as inline functions after table declarations.

When these new functions are declared, a user-defined
explicitly-defaulted default constructor and move constructor are also
emitted.

The copy assignment operator uses the copy-and-swap idiom to provide
strong exception safety, at the expense of keeping 2 full table copies
in memory temporarily.

fixes #5783
This commit is contained in:
Jean-François Roy
2022-01-29 14:24:24 -08:00
committed by GitHub
parent 5993338ee3
commit 43203984f7
7 changed files with 547 additions and 59 deletions

View File

@@ -239,6 +239,10 @@ struct MonsterT : public flatbuffers::NativeTable {
std::vector<flatbuffers::unique_ptr<MyGame::Sample::WeaponT>> weapons{};
MyGame::Sample::EquipmentUnion equipped{};
std::vector<MyGame::Sample::Vec3> path{};
MonsterT() = default;
MonsterT(const MonsterT &o);
MonsterT(MonsterT&&) FLATBUFFERS_NOEXCEPT = default;
MonsterT &operator=(MonsterT o) FLATBUFFERS_NOEXCEPT;
};
struct Monster FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
@@ -555,6 +559,32 @@ inline bool operator!=(const MonsterT &lhs, const MonsterT &rhs) {
}
inline MonsterT::MonsterT(const MonsterT &o)
: pos((o.pos) ? new MyGame::Sample::Vec3(*o.pos) : nullptr),
mana(o.mana),
hp(o.hp),
name(o.name),
inventory(o.inventory),
color(o.color),
equipped(o.equipped),
path(o.path) {
weapons.reserve(o.weapons.size());
for (const auto &v : o.weapons) { weapons.emplace_back((v) ? new MyGame::Sample::WeaponT(*v) : nullptr); }
}
inline MonsterT &MonsterT::operator=(MonsterT o) FLATBUFFERS_NOEXCEPT {
std::swap(pos, o.pos);
std::swap(mana, o.mana);
std::swap(hp, o.hp);
std::swap(name, o.name);
std::swap(inventory, o.inventory);
std::swap(color, o.color);
std::swap(weapons, o.weapons);
std::swap(equipped, o.equipped);
std::swap(path, o.path);
return *this;
}
inline MonsterT *Monster::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
auto _o = std::unique_ptr<MonsterT>(new MonsterT());
UnPackTo(_o.get(), _resolver);