mirror of
https://github.com/google/flatbuffers.git
synced 2026-06-09 22:56:27 +00:00
Fix memory leak on cpp object api (#5761)
Previously UnPack would allocate data with new and assign it to a raw pointer. This behavior makes it possible for the pointer to be leaked in case of OOM. This commit defaults to use the user specified pointer (which needs to implement a move constructor, a .get() and a .release() operators), thus preventing these leaks.
This commit is contained in:
@@ -117,7 +117,7 @@ std::string FlatCompiler::GetUsageString(const char *program_name) const {
|
||||
" T::c_str(), T::length() and T::empty() must be supported.\n"
|
||||
" The custom type also needs to be constructible from std::string\n"
|
||||
" (see the --cpp-str-flex-ctor option to change this behavior).\n"
|
||||
" --cpp-str-flex-ctor Don't construct custom string types by passing std::string\n"
|
||||
" --cpp-str-flex-ctor Don't construct custom string types by passing std::string\n"
|
||||
" from Flatbuffers, but (char* + length).\n"
|
||||
" --cpp-std CPP_STD Generate a C++ code using features of selected C++ standard.\n"
|
||||
" Supported CPP_STD values:\n"
|
||||
@@ -353,8 +353,7 @@ int FlatCompiler::Compile(int argc, const char **argv) {
|
||||
} else if (arg == "--flexbuffers") {
|
||||
opts.use_flexbuffers = true;
|
||||
} else if (arg == "--cpp-std") {
|
||||
if (++argi >= argc)
|
||||
Error("missing C++ standard specification" + arg, true);
|
||||
if (++argi >= argc) Error("missing C++ standard specification" + arg, true);
|
||||
opts.cpp_std = argv[argi];
|
||||
} else {
|
||||
for (size_t i = 0; i < params_.num_generators; ++i) {
|
||||
|
||||
@@ -2705,14 +2705,21 @@ class CppGenerator : public BaseGenerator {
|
||||
code_.SetValue("STRUCT_NAME", Name(struct_def));
|
||||
code_.SetValue("NATIVE_NAME",
|
||||
NativeName(Name(struct_def), &struct_def, opts_));
|
||||
auto native_name =
|
||||
NativeName(WrapInNameSpace(struct_def), &struct_def, parser_.opts);
|
||||
code_.SetValue("POINTER_TYPE",
|
||||
GenTypeNativePtr(native_name, nullptr, false));
|
||||
|
||||
if (opts_.generate_object_based_api) {
|
||||
// Generate the X::UnPack() method.
|
||||
code_ +=
|
||||
"inline " + TableUnPackSignature(struct_def, false, opts_) + " {";
|
||||
code_ += " auto _o = new {{NATIVE_NAME}}();";
|
||||
code_ += " UnPackTo(_o, _resolver);";
|
||||
code_ += " return _o;";
|
||||
|
||||
code_ +=
|
||||
" {{POINTER_TYPE}} _o = {{POINTER_TYPE}}(new {{NATIVE_NAME}}());";
|
||||
code_ += " UnPackTo(_o.get(), _resolver);";
|
||||
code_ += " return _o.release();";
|
||||
|
||||
code_ += "}";
|
||||
code_ += "";
|
||||
|
||||
|
||||
Reference in New Issue
Block a user