mercredi 25 janvier 2017

C++ Cast double to char and replace into std::array

For RAM optimization purpose, I need to store my data as a std::array where N is the "templated size_t" size of the array. I need to managed huge amount of "Line" object that contains any kind of data (numerical and char).

So my Line class is:

template<size_t NByte>
class Line {
public:
  Line (std::array<char, NByte> data, std::vector<size_t> offset) :
      _data(data), _offset(offset) {}

  template<typename T>
  T getValue (const size_t& index) const {
    return *reinterpret_cast<const T*>(_data.data() + _offset[index]);
  }

  template<typename T>
  void setValue (const size_t& index, const T value) const {
    char * new_value = const_cast<char *>(reinterpret_cast<const char *>(&value));
    std::move(new_value, new_value + sizeof(T), const_cast<char *>(_data.data() + _offset[index]));
  }

private:
  std::array<char, NByte> _data;
  std::vector<size_t> _offset;
};

My question is:

  • Is it a better way to do the setter and getter function?
  • This is it robust against memory leak?
  • Is it any problem to use this code in production/release?

Aucun commentaire:

Enregistrer un commentaire