[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

@@ -265,6 +265,10 @@ inline bool operator!=(const ArrayStruct &lhs, const ArrayStruct &rhs) {
struct ArrayTableT : public flatbuffers::NativeTable {
typedef ArrayTable TableType;
flatbuffers::unique_ptr<MyGame::Example::ArrayStruct> a{};
ArrayTableT() = default;
ArrayTableT(const ArrayTableT &o);
ArrayTableT(ArrayTableT&&) FLATBUFFERS_NOEXCEPT = default;
ArrayTableT &operator=(ArrayTableT o) FLATBUFFERS_NOEXCEPT;
};
struct ArrayTable FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
@@ -331,6 +335,15 @@ inline bool operator!=(const ArrayTableT &lhs, const ArrayTableT &rhs) {
}
inline ArrayTableT::ArrayTableT(const ArrayTableT &o)
: a((o.a) ? new MyGame::Example::ArrayStruct(*o.a) : nullptr) {
}
inline ArrayTableT &ArrayTableT::operator=(ArrayTableT o) FLATBUFFERS_NOEXCEPT {
std::swap(a, o.a);
return *this;
}
inline ArrayTableT *ArrayTable::UnPack(const flatbuffers::resolver_function_t *_resolver) const {
auto _o = std::unique_ptr<ArrayTableT>(new ArrayTableT());
UnPackTo(_o.get(), _resolver);