spiegel-keyman/core/src/option.hpp
Marc Durdin 7ec4832edc fix(core): memory management of options in action struct
Fixes #10067.

Management of memory for persisted options was wrong in the action
struct, as the members key and value would be freed immediately after
being added to the temporary vector (because the vector was of the
struct rather than of the class).

Given the struct is a C struct, we need the memory management to be
explicit, so we now release() each option into the vector as we create
it, which means that its member values will not be freed when the option
is then immediately deleted. (This allows us to use the initial copy of
the members of option that option() constructor does.)

Added the release() function as that was a relatively clear way of
indicating that the contents of the structure are now owned by the
caller, following the pattern from std::unique_ptr.

Finally, the unit test for persisted options was in the action_api.cpp
test module, but it was never called, so this was not being tested. Now
it is.
2023-11-24 07:52:31 +10:00

98 lines
2 KiB
C++

/*
Copyright: © 2018 SIL International.
Description: Internal option key value map class and adaptor class for
the API.
Create Date: 2 Oct 2018
Authors: Tim Eves (TSE)
History: 2 Oct 2018 - TSE - Refactored out of km_core_options_api.cpp.
7 Nov 2018 - TSE - Refactored into option.hpp & option.cpp.
*/
#pragma once
#include <string>
#include <keyman/keyman_core_api.h>
// Forward declarations
class json;
namespace km {
namespace core
{
struct option : public km_core_option_item
{
option(): km_core_option_item KM_CORE_OPTIONS_END {}
option(option const &);
option(option &&);
option(km_core_option_scope, char16_t const *, char16_t const *);
option(km_core_option_scope, std::u16string const &,
std::u16string const &);
~option() noexcept;
option & operator=(option const & rhs);
option & operator=(option && rhs);
/**
* Returns contents of this object as a C struct, releasing memory
* management of key and value, and invalidates this object.
*/
km_core_option_item release();
bool empty() const;
};
inline
option::option(km_core_option_scope s,
std::u16string const & k, std::u16string const & v)
: option(s, k.c_str(), v.c_str())
{}
inline
option::option(option const & rhs)
: option(km_core_option_scope(rhs.scope), rhs.key, rhs.value) {}
inline
option::option(option && rhs) : option()
{
std::swap(key, rhs.key);
std::swap(value, rhs.value);
scope = rhs.scope;
}
inline
option::~option() noexcept
{
delete [] key;
delete [] value;
}
inline
option & option::operator=(option && rhs) {
delete [] key;
delete [] value;
return *new (this) option(std::move(rhs));
}
inline
option & option::operator=(option const & rhs)
{
delete [] key;
delete [] value;
return *new (this) option(rhs);
}
inline
bool option::empty() const {
return key == nullptr;
}
} // namespace core
} // namespace km