简体   繁体   中英

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

For RAM optimization purpose, I need to store my data as a std::array<char, N> where N is the "templated size_t" size of the array. I need to manage a huge amount of "Line" objects that contain 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 questions are:

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

Edit: The question behind those is: Is there any other way to work with binary data in memory and provide "human understandable" interface for final user through setter and getter?

Is there any problem in using this code in production/release?

Yes, this code is platform-dependent.

The data will be stored differently in Big-Endian platforms and in Little-Endian platforms.

If your're counting on two systems communicating with each other (transmitting and receiving this data), then you will have to make sure that both sides use platforms of the same Endianness.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM