[odb-users] custom type mapping using value_traits specialization and memory leak prevention

Sten Kultakangas ratkaisut at gmail.com
Sat May 2 11:50:54 EDT 2020


I am implementing nvarchar <-> utf8-encoded std::string database type
mapping. Everything seems to be easy for nvarchar fields not exceeding
certain limit in length:

#include <cstring>
#include <Poco/UnicodeConverter.h>
#include "core/db_types.h"

using Poco::UnicodeConverter;
using namespace std;

namespace odb {
namespace mssql {

void value_traits<string, id_nstring>::set_value(string &value,
const ucs2_char *buffer, size_t buffer_size, bool is_null)
  if(is_null) value = "";
  else UnicodeConverter::convert(buffer, buffer_size, value);

void value_traits<string, id_nstring>::set_image(ucs2_char *buffer,
size_t buffer_size, size_t &actual_size, bool &is_null, const string &value)
  Poco::UTF16String utf16;
  UnicodeConverter::convert(value, utf16);

  is_null = false;
  actual_size = utf16.size();
  if(actual_size > buffer_size) actual_size = buffer_size;
  memcpy(buffer, utf16.data(), actual_size * sizeof(ucs2_char));


However, i would like to implement the specialization for the
id_long_nstring type also so i can work with nvarchar fields exceeding the
length limit. The main concern is whether the callback is called with
chunk_type=chunk_last even in the case of an exception thrown due to an I/O
error. I could not find any destructor to prove that the callback will be
called in such scenario. If the callback is not called in the case of an
I/O error, the non-trivially destructible object referenced in the "user
context" parameter will not be destroyed and a memory leak will occur. If
there is such a limitation, then i must design a trivially destructible
state machine object and place it in the provided buffer to prevent memory

Can you confirm my concern that the callback will not be called in the case
of an exception thrown during the set_value/set_image operation for the
id_long_nstring type ?

Best regards,
Sten Kultakangas

More information about the odb-users mailing list